<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Contents extends BaseController {

	public function __construct() {
        parent::__construct();
        // 后台初始化方法
        $this->admin_init();
        // 检查用户身份
        if($this->userType != USER_TYPE_SCHOOL && $this->userType != USER_TYPE_TEACHER) redirect(admin_url("login"));
        // 加载类库
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        $this->load->model('contentModel');
        $this->load->model('dataModel');
    }
    // 获取该校区的班级id数组
    private function _get_campus_class_id_Arr() {
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['isDelete'] = 0;
        $classList = $this->classesModel->get_class_list($params);
        $idArr = array();
        if(!empty($classList)) {
            foreach($classList as $class) {
                array_push($idArr, $class['id']);
            }
        }
        return $idArr;
    }

    // 作业
    public function homework(){
        // 获取年级
        $gradeParams['isDelete'] = 0;
        $gradeParams['schoolId'] = $this->rmxSchool['id'];
        $gradeParams['campusId'] = $this->campusInfo['id'];
        $this->gradeList = $this->classesModel->get_grade_list($gradeParams);
        // 只获取行政班
        $gradeParams['classType'] = CLASSES_TYPE_NORMAL;

        // 获取班级列表
        $classData = $this->classesModel->get_class_list($gradeParams);
        $classArray = array();
        foreach($classData as $class) {
            $classArray[$class['grade_id']][] = array(
                "id" => $class['id'],
                "name" => $class['class_name']
            );
        }
        $this->classList = json_encode($classArray);

        // echo '<pre>';var_export($this->rmxUser);exit;

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "homework");
    }
    // ajax获取作业列表
    public function get_homework_list() {
        // 默认获取当前校区的所有班级
        $classIdArr = $this->_get_campus_class_id_Arr();
        // 筛选班级
        if($this->get('class_id') && 0 !== $this->get('class_id')) {
            $classId = $this->get('class_id');
            $data['classId'] = $classId;
            $totalParams['classId'] = $classId;
        }
        // 搜索标题
        if($this->get('title') && '' !== trim($this->get('title'))) {
            $title = trim($this->get('title'));
        }
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        // 过滤软删除
        $data['isDelete'] = 0;
        // 过滤班级数组
        if($classIdArr) {
            $data['classIdArr'] = $classIdArr;
        }
        // 过滤标题
        if(isset($title)) {
            $data['title'] = $title;
        }
        // 教师权限登录时，只获取任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER && isset($this->rmxUser['classIdArr'])) {
            $data['classIdArr'] = $this->rmxUser['classIdArr'];
        }
        $homeworkList = $this->contentModel->get_homework_list($data);
        foreach($homeworkList as &$homework) {
            // 查询作业发送班级
            $params['classId'] = $homework['class_id'];
            // 过滤软删除
            $params['isDelete'] = 0;
            $homework['classList'] = $this->classesModel->get_grade_class_list($params);
            // 获取科目信息
            $lessonInfo = $this->schoolModel->get_lesson_info($homework['lesson_id']);
            $homework['lessonName'] = $lessonInfo ? $lessonInfo['lesson_name'] : '';
            // 判断当前用户有没编辑权限
            $homework['role_change'] = true;
            if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
                $homework['role_change'] = false;
                $idArr = explode(',', $homework['class_id']);
                foreach($idArr as $id) {
                    if(in_array($id, $this->rmxUser['classIdArr'])) {
                        $homework['role_change'] = true;
                    }
                }
            }
        }
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        // 过滤班级数组
        if($classIdArr) {
            $totalParams['classIdArr'] = $classIdArr;
        }
        // 过滤标题
        if(isset($title)) {
            $totalParams['title'] = $title;
        }
        // 教师权限登录时，只获取任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER && isset($this->rmxUser['classIdArr'])) {
            $totalParams['classIdArr'] = $this->rmxUser['classIdArr'];
        }

        $total = $this->contentModel->get_homework_list($totalParams);
        // 返回值
        exit(admin_table_data($total, $homeworkList));   
    }
    // 编辑作业页面
    public function homework_edit($homeworkId=0){
        if(!empty($homeworkId)) {
            $this->homeworkInfo = $this->contentModel->get_homework_info($homeworkId);
            if(trim($this->homeworkInfo['imgs'])) {
                $this->homeworkInfo['imgArr'] = explode(',', $this->homeworkInfo['imgs']);
            }
            if(trim($this->homeworkInfo['file'])) {
                $this->homeworkInfo['fileArr'] = json_decode($this->homeworkInfo['file'], true);
                // office文件支持预览
                foreach($this->homeworkInfo['fileArr'] as &$file) {
                    // if(preg_match("/^.*\.(doc|docx|ppt|pptx|xls|xlsx)$/", $file['link'])) {
                    //     $file['linkPreview'] = 'https://view.officeapps.live.com/op/view.aspx?src=' . $file['link'];
                    // } else {
                        $file['linkPreview'] = $file['link'];
                    // }
                }
            }
        }
        // var_export($this->homeworkInfo);exit;
        // 年级班级列表
        $params['isDelete'] = 0;
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['getLevelData'] = true;
        // 教师权限只能发布任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
            $params['classId'] = $this->rmxUser['class_ids'];
        }
        // 只获取行政班
        $params['classType'] = CLASSES_TYPE_NORMAL;
        $this->gradeArray = $this->classesModel->get_grade_class_list($params);
        // 科目列表
        $lessonParams['schoolId'] = $this->rmxSchool['id'];
        $lessonParams['isDelete'] = 0;
        $lessonList = $this->schoolModel->get_lesson_list($lessonParams);
        // 使用id作为键值
        $lessonList = array_value_to_key($lessonList, 'id');
        // 教师权限只能选择任课班级的科目
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
            // $params['classId'] = $this->rmxUser['class_ids'];
            // 任课科目
            $this->load->model('staffModel');
            $coachParams['teacherId'] = $this->rmxUser['id'];
            $coachParams['coachType'] = COACH_TYPE_TEACHER; 
            $coachList = $this->staffModel->get_coach_list($coachParams);
            $coachSubjectIdArr = array();
            foreach($coachList as $coach) {
                $subjectIds = $coach['subject_ids'];
                $subjectIdArr = explode(',', $subjectIds);
                $coachSubjectIdArr = array_merge($coachSubjectIdArr, $subjectIdArr);
            }
            $coachSubjectIdArr = array_unique($coachSubjectIdArr);
            $coachSubjectArr = array();
            foreach($coachSubjectIdArr as $coachSubjectId) {
                if(isset($lessonList[$coachSubjectId])) {
                    array_push($coachSubjectArr, $lessonList[$coachSubjectId]);
                }
            }
            $this->lessonList = $coachSubjectArr;
        } else {
            $this->lessonList = $lessonList;
        }
        // 生成又拍云签名
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "homework_edit");
    }
    // 保存作业
    public function save_homework_action(){
        $homeworkId = $this->post("id");
        $homeworkTitle = $this->post("homework_title");
        $homeworkClass = $this->post("homework_class");
        $homeworkContent = $this->post("homework_content", false);
        $materialArr = $this->post('material');
        $file = $this->post('file') ? json_encode($this->post('file'), JSON_UNESCAPED_UNICODE) : '';
        $canSubmit = $this->post('can_submit') ? $this->post('can_submit') : 0;
        // 参数检查
        if(!$homeworkTitle) throw new Exception("请填写班级作业标题");
        if(!$homeworkClass) throw new Exception("请选择发布班级");
        if(!$homeworkContent) throw new Exception("请填写班级作业内容");
        if(empty($this->post("lesson_id"))) throw new Exception("请选择科目");
        if($materialArr) {
            if(9 < count($materialArr)) {
                throw new Exception("最多只能上传9张图片");
            }
            $material = implode(',', $materialArr);
        } else {
            $material = '';
        }
        if($this->post('file') && count($this->post('file')) > 9) {
            throw new Exception("最多只能上传9个附件");
        }
        // 提示信息
        $msg = $homeworkId ? '修改班级作业成功' : '发布班级作业成功';
        // 入库
        $data['class_id'] = $homeworkClass;
        $data['lesson_id'] = $this->post("lesson_id");
        $data['homework_title'] = $homeworkTitle;
        $data['homework_content'] = $homeworkContent;
        $data['imgs'] = $material;
        $data['file'] = $file;
        $data['can_submit'] = $canSubmit;
        $data['updatetime'] = date("Y-m-d H:i:s");
        
        // 操作
        $action = '';
        if($homeworkId) {
            $action = 'update';
            $this->db->update(ContentModel::$homeworkTable, $data, "id='{$homeworkId}'");
        } else {
            $action = 'insert';
            $data['school_id'] = $this->rmxSchool['id'];
            $data['campus_id'] = $this->campusInfo['id'];
            $data['user_id'] = $this->rmxUser['id'];
            $data['createtime'] = $data['updatetime'];
            $this->db->insert(ContentModel::$homeworkTable, $data);

            $homeworkId = $this->db->insert_id();
        }
        // 推送消息到客户端
        $this->load->library('socket');
        $this->socket->send_homework_msg($this->rmxSchool['id'], $homeworkClass, $homeworkId);

        // 修改不发送模板消息
        if($action == 'insert') {
            // 获取科目名称
            $lesson = $this->schoolModel->get_lesson_info($this->post("lesson_id"));
            if($lesson) {
                $lessonName = $lesson['lesson_name'];
            } else {
                $lessonName = '';
            }
            // 发布班级，如大于3个，截取前3个班级
            $classNameStr = $this->_get_class_name_str($homeworkClass);
            $arr = explode('、', $classNameStr);
            if(count($arr) > 3) {
                $newArr = array_slice($arr, 0, 3);
                $classNameStr = implode('、', $newArr) . '...';
            }
            $keyword2 = $homeworkTitle;
            if($lessonName) {
                $keyword2 = '（' . $lessonName . '）' . $homeworkTitle;
            }
            $data = array(
                'keyword1' => array(
                    'value' => $classNameStr
                ),
                'keyword2' => array(
                    'value' => $keyword2
                )
            );
            $url =wx_url('classes/homework_detail/') . $homeworkId;

            // 获取学生列表
            $stuParams['isDelete'] = 0;
            $stuParams['schoolId'] = $this->rmxSchool['id'];
            $stuParams['classSet'] = $homeworkClass;
            $students = $this->schoolModel->get_student_list($stuParams);
            if($students) {
                $this->load->model('wxUserModel');
                // 截取成100个
                $arr = array_chunk($students, 100);
                foreach($arr as $studentArr) {
                    $processDataArr = array();
                    foreach($studentArr as $student) {
                        array_push($processDataArr, array(
                            'student_id' => $student['id'],
                            'data' => $data 
                        ));
                    }
                    $this->db->insert(WxUserModel::$wxTemplateProcessTable, array(
                        'template_id' => WX_TEMPLATE_HOMEWORK,
                        'type' => 'student',
                        'data' => json_encode($processDataArr, JSON_UNESCAPED_UNICODE),
                        'url' => $url
                    ));
                }
            }
        }

        // 返回值
        exit(json($msg, true));
    }

    // 删除作业
    public function delete_homework_action() {
        $id = $this->post('id');
        $data = array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(ContentModel::$homeworkTable, $data, array('id' => $id));
        exit(json('删除成功', true));
    }

    // 动态
    public function news(){
        // 获取年级
        $gradeParams['isDelete'] = 0;
        $gradeParams['schoolId'] = $this->rmxSchool['id'];
        $gradeParams['campusId'] = $this->campusInfo['id'];
        $this->gradeList = $this->classesModel->get_grade_list($gradeParams);
        // 只获取行政班
        $gradeParams['classType'] = CLASSES_TYPE_NORMAL;

        // 获取班级列表
        $classData = $this->classesModel->get_class_list($gradeParams);
        $classArray = array();
        foreach($classData as $class) {
            $classArray[$class['grade_id']][] = array(
                "id" => $class['id'],
                "name" => $class['class_name']
            );
        }
        $this->classList = json_encode($classArray);
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "news");
    }
    // 获取动态页面的班级列表
    // public function get_news_class_list(){
    //     // 班级id筛选
    //     if($this->get("gradeId")) $totalParams['gradeId'] = $data['gradeId'] = $this->get("gradeId");
    //     // 获取数据条数
    //     $totalParams['getRowNumber'] = true;
    //     $totalParams['schoolId'] = $this->rmxSchool['id'];
    //     $totalParams['campusId'] = $this->campusInfo['id'];
    //     // 过滤软删除
    //     $totalParams['isDelete'] = 0;
    //     $total = $this->classesModel->get_class_list($totalParams);
    //     // 获取数据
    //     $data['pageStart'] = $this->get('start');
    //     $data['pageSize']= $this->get("length");
    //     $data['schoolId'] = $this->rmxSchool['id'];
    //     $data['campusId'] = $this->campusInfo['id'];
    //     // 过滤软删除
    //     $data['isDelete'] = 0;
    //     $classList = $this->classesModel->get_class_list($data);
    //     foreach($classList as &$class) {
    //         $class['className'] = $class['class_name'];
    //     }
    //     // 返回值
    //     exit(admin_table_data($total, $classList));   
    // }
    // 动态列表
    public function news_list($classId){
        $this->classInfo = $classInfo = $this->classesModel->get_class_info($classId);
        if(!$classInfo || $classInfo['school_id'] != $this->rmxSchool['id'])show_error("参数不错，班级不存在");

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "news_list");
    }
    // ajax获取动态列表
    public function get_news_list() {
        // 默认获取当前校区的所有班级
        $classIdArr = $this->_get_campus_class_id_Arr();
        // 筛选班级
        if($this->get('class_id') && 0 !== $this->get('class_id')) {
            $classId = $this->get('class_id');
            $data['classId'] = $classId;
            $totalParams['classId'] = $classId;
        }
        // 搜索标题
        if($this->get('title') && '' !== trim($this->get('title'))) {
            $title = trim($this->get('title'));
        }
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        // 过滤软删除
        $data['isDelete'] = 0;
        // 过滤班级数组
        if($classIdArr) {
            $data['classIdArr'] = $classIdArr;
        }
        // 过滤标题
        if(isset($title)) {
            $data['title'] = $title;
        }
        // 教师权限登录时，只获取任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER && isset($this->rmxUser['classIdArr'])) {
            $data['classIdArr'] = $this->rmxUser['classIdArr'];
        }
        $newsList = $this->contentModel->get_news_list($data);
        foreach($newsList as &$news) {
            // 查询动态发送班级
            $params['classId'] = $news['class_id'];
            // 过滤软删除
            $params['isDelete'] = 0;
            $news['classList'] = $this->classesModel->get_grade_class_list($params);
            // 判断当前用户有没编辑权限
            $news['role_change'] = true;
            if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
                $news['role_change'] = false;
                $idArr = explode(',', $news['class_id']);
                foreach($idArr as $id) {
                    if(in_array($id, $this->rmxUser['classIdArr'])) {
                        $news['role_change'] = true;
                    }
                }
            }
        }
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        // 过滤班级数组
        if($classIdArr) {
            $totalParams['classIdArr'] = $classIdArr;
        }
        // 过滤标题
        if(isset($title)) {
            $totalParams['title'] = $title;
        }
        // 教师权限登录时，只获取任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER && isset($this->rmxUser['classIdArr'])) {
            $totalParams['classIdArr'] = $this->rmxUser['classIdArr'];
        }
        $total = $this->contentModel->get_news_list($totalParams);
        // 过滤待发布
        $countIsCron = 0;
        // echo '<pre>';var_export($newsList);exit;
        foreach($newsList as $key => $item) {
            // 待发布动态仅对发布人和班主任可见
            if($item['is_cron'] == 1) {
                if($item['user_id'] == $this->rmxUser['id']) {
                    continue;
                }
                $classIds = $news['class_id'];
                $classIdArr = explode(',', $classIds);
                
                // 获取班主任对应的班级列表
                $coachParams['teacherId'] = $this->rmxUser['id'];
                $coachParams['coachType'] = COACH_TYPE_MASTER; 
                $this->load->model('staffModel');
                $coachList = $this->staffModel->get_coach_list($coachParams);
                $isMaster = 0;
                foreach($coachList as $coach) {
                    $idArr = explode(',', $coach['class_ids']);
                    foreach($idArr as $id) {
                       if(in_array($id, $classIdArr)) {
                           $isMaster = 1;
                       }
                    }
                }
                if($isMaster) {
                   continue; 
                }
                // 过滤动态
                unset($newsList[$key]);
                $countIsCron ++;
            }
            // 重新排序
            $newsList = array_values($newsList);
        }
        // var_export($countIsCron);exit;

        if($total > 0) {
            $total = $total - $countIsCron;
        }

        // 返回值
        exit(admin_table_data($total, $newsList));   
    }
    // 编辑动态页面
    public function news_edit($newsId = 0){
        if(!empty($newsId)) {
            $this->newsInfo = $this->contentModel->get_news_info($newsId);
            if(trim($this->newsInfo['imgs'])) {
                $this->newsInfo['imgArr'] = explode(',', $this->newsInfo['imgs']);
            }
            if(trim($this->newsInfo['audios'])) {
                $this->newsInfo['audioArr'] = json_decode($this->newsInfo['audios'], true);
            }
            if(trim($this->newsInfo['videos'])) {
                $videoArr = json_decode($this->newsInfo['videos'], true);
                foreach($videoArr as &$video) {
                    if(isset($video['old_link']) && stripos($video['old_link'], '.MOV') === false) {
                        $video['href'] = $video['old_link'];
                    } else {
                        $video['href'] = $video['link'];
                    }
                }
                $this->newsInfo['videoArr'] = $videoArr;
                // echo '<pre>';var_export($this->newsInfo['videoArr']);exit;
            }
        }
        $params['isDelete'] = 0;
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['getLevelData'] = true;
        // 教师权限只能发布任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
            $params['classId'] = $this->rmxUser['class_ids'];
        }
        // 只获取行政班
        $params['classType'] = CLASSES_TYPE_NORMAL;

        $this->gradeArray = $this->classesModel->get_grade_class_list($params);
        // 生成又拍云签名
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "news_edit");
    }
    // 保存班级动态
    public function save_news_action(){
        $newsId = $this->post("id");
        $newsTitle = $this->post("news_title");
        $newsClass = $this->post("news_class");
        $newsContent = $this->post("news_content", false);
        $materialArr = $this->post('material');
        $audios = $this->post('audio_arr') ? json_encode($this->post('audio_arr'), JSON_UNESCAPED_UNICODE) : '';
        $isCron = $this->post('is_cron') ? $this->post('is_cron') : 0;
        $videos = $this->post('video_arr') ? json_encode($this->post('video_arr'), JSON_UNESCAPED_UNICODE) : '';
        // 参数检查
        if(!$newsTitle) throw new Exception("请填写班级动态标题");
        if(!$newsClass) throw new Exception("请选择班级动态发送班级");
        if(!$newsContent) throw new Exception("请填写班级动态内容");
        if($materialArr) {
            if(9 < count($materialArr)) {
                throw new Exception("最多只能上传9张图片");
            }
            $material = implode(',', $materialArr);
        } else {
            $material = '';
        }
        if($isCron) {
            $cronTime = $this->post('crontime');
            if(empty($cronTime)) {
                if(!$cronTime) throw new Exception("请选择定时发布时间");
            }
        } else {
            $cronTime = '';
        }
        if($this->post('video_arr') && 9 < count($this->post('video_arr'))) {
            throw new Exception("最多只能上传9个视频");
        }
        // 提示信息
        $msg = $newsId ? '修改班级动态成功' : '发布班级动态成功';

        // 入库
        $data['class_id'] = $newsClass;
        $data['news_title'] = $newsTitle;
        $data['news_content'] = $newsContent;
        $data['imgs'] = $material;
        $data['videos'] = $videos;
        $data['audios'] = $audios;
        $data['is_cron'] = $isCron;
        $data['crontime'] = $cronTime;
        $data['updatetime'] = date("Y-m-d H:i:s");
        // 操作
        $action = '';
        if($newsId) {
            $action = 'update';
            $this->db->update(ContentModel::$newsTable, $data, "id='{$newsId}'");
        } else {
            $action = 'insert';
            $data['school_id'] = $this->rmxSchool['id'];
            $data['campus_id'] = $this->campusInfo['id'];
            $data['user_id'] = $this->rmxUser['id'];
            $data['createtime'] = $data['updatetime'];
            $this->db->insert(ContentModel::$newsTable, $data);

            $newsId = $this->db->insert_id();
        }

        if(!$isCron) {
            // 推送消息到客户端
            $this->load->library('socket');
            $this->socket->send_news_msg($this->rmxSchool['id'], $newsClass, $newsId);

            // 修改不发送模板消息
            if($action == 'insert') {
                // 发布班级，如大于3个，截取前3个班级
                $classNameStr = $this->_get_class_name_str($newsClass);
                $arr = explode('、', $classNameStr);
                if(count($arr) > 3) {
                    $newArr = array_slice($arr, 0, 3);
                    $classNameStr = implode('、', $newArr) . '...';
                }
                $data = array(
                    'keyword1' => array(
                        'value' => $classNameStr
                    ),
                    'keyword2' => array(
                        'value' => $this->rmxUser['realname'] ? $this->rmxUser['realname'] : $this->rmxUser['username']
                    ),
                    'keyword3' => array(
                        'value' => date('Y-m-d H:i:s')
                    ),
                    'keyword4' =>  array(
                        'value' => '类型：班级动态'
                    )
                );
                $url =wx_url('classes/news_detail/') . $newsId;
                // 发送模板消息
                // $this->load->library('wxtemplate');
                // $this->wxtemplate->send_template_msg($newsClass, WX_TEMPLATE_NOTIFY, $data, $url);
                // // 后台进程
                // $this->load->model('wxUserModel');
                // $this->db->insert(WxUserModel::$wxTemplateProcessTable, array(
                //     'template_id' => WX_TEMPLATE_NOTIFY,
                //     'type' => 'class',
                //     'class_ids' => $newsClass,
                //     'data' => json_encode($data, JSON_UNESCAPED_UNICODE),
                //     'url' => $url
                // ));

                // 获取学生列表
                $stuParams['isDelete'] = 0;
                $stuParams['schoolId'] = $this->rmxSchool['id'];
                $stuParams['classSet'] = $newsClass;
                $students = $this->schoolModel->get_student_list($stuParams);
                if($students) {
                    $this->load->model('wxUserModel');
                    // 截取成100个
                    $arr = array_chunk($students, 100);
                    foreach($arr as $studentArr) {
                        $processDataArr = array();
                        foreach($studentArr as $student) {
                            array_push($processDataArr, array(
                                'student_id' => $student['id'],
                                'data' => $data 
                            ));
                        }
                        $this->db->insert(WxUserModel::$wxTemplateProcessTable, array(
                            'template_id' => WX_TEMPLATE_NOTIFY,
                            'type' => 'student',
                            'data' => json_encode($processDataArr, JSON_UNESCAPED_UNICODE),
                            'url' => $url
                        ));
                    }
                }
            }
        }

        // 返回值
        exit(json($msg, true));
    }

    // 删除动态
    public function delete_news_action() {
        $id = $this->post('id');
        $data = array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(ContentModel::$newsTable, $data, array('id' => $id));
        exit(json('删除成功', true));
    }

    // 通知
    public function notify(){
        // 获取年级
        $gradeParams['isDelete'] = 0;
        $gradeParams['schoolId'] = $this->rmxSchool['id'];
        $gradeParams['campusId'] = $this->campusInfo['id'];
        $this->gradeList = $this->classesModel->get_grade_list($gradeParams);
        // 只获取行政班
        $gradeParams['classType'] = CLASSES_TYPE_NORMAL;
        
        // 获取班级列表
        $classData = $this->classesModel->get_class_list($gradeParams);
        $classArray = array();
        foreach($classData as $class) {
            $classArray[$class['grade_id']][] = array(
                "id" => $class['id'],
                "name" => $class['class_name']
            );
        }
        $this->classList = json_encode($classArray);
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "notify");
    }
    // 获取通知页面的班级列表
    // public function get_notify_class_list(){
    //     // 班级id筛选
    //     if($this->get("gradeId")) $totalParams['gradeId'] = $data['gradeId'] = $this->get("gradeId");
    //     // 获取数据条数
    //     $totalParams['getRowNumber'] = true;
    //     $totalParams['schoolId'] = $this->rmxSchool['id'];
    //     $totalParams['campusId'] = $this->campusInfo['id'];
    //     // 过滤软删除
    //     $totalParams['isDelete'] = 0;
    //     $total = $this->classesModel->get_class_list($totalParams);
    //     // 获取数据
    //     $data['pageStart'] = $this->get('start');
    //     $data['pageSize']= $this->get("length");
    //     $data['schoolId'] = $this->rmxSchool['id'];
    //     $data['campusId'] = $this->campusInfo['id'];
    //     // 过滤软删除
    //     $data['isDelete'] = 0;
    //     $classList = $this->classesModel->get_class_list($data);
    //     foreach($classList as &$class) {
    //         $class['className'] = $class['class_name'];
    //     }
    //     // 返回值
    //     exit(admin_table_data($total, $classList));   
    // }
    // 通知列表
    public function notify_list($classId){
        $this->classInfo = $classInfo = $this->classesModel->get_class_info($classId);
        if(!$classInfo || $classInfo['school_id'] != $this->rmxSchool['id'])show_error("参数错误，班级不存在");

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "notify_list");
    }
    // ajax获取通知列表
    public function get_notify_list() {
        // 默认获取当前校区的所有班级
        $classIdArr = $this->_get_campus_class_id_Arr();
        // 筛选班级
        if($this->get('class_id') && 0 !== $this->get('class_id')) {
            $classId = $this->get('class_id');
            $data['classId'] = $classId;
            $totalParams['classId'] = $classId;
        }
        // 搜索标题
        if($this->get('title') && '' !== trim($this->get('title'))) {
            $title = trim($this->get('title'));
        }
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        // 过滤软删除
        $data['isDelete'] = 0;
        $data['orderByFirst'] = array('order' => 'is_top', 'sort' =>'DESC');
        $data['orderBy'] = array('order' => 'updatetime', 'sort' =>'DESC');
        // 过滤班级数组
        if($classIdArr) {
            $data['classIdArr'] = $classIdArr;
        }
        // 过滤标题
        if(isset($title)) {
            $data['title'] = $title;
        }
        // 教师权限登录时，只获取任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER && isset($this->rmxUser['classIdArr'])) {
            $data['classIdArr'] = $this->rmxUser['classIdArr'];
        }
        $notifyList = $this->contentModel->get_notify_list($data);
        foreach($notifyList as &$notify) {
            // 查询通知发送班级
            $params['classId'] = $notify['class_id'];
            // 过滤软删除
            $params['isDelete'] = 0;
            $notify['classList'] = $this->classesModel->get_grade_class_list($params);
            // 判断当前用户有没编辑权限
            $notify['role_change'] = true;
            if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
                $notify['role_change'] = false;
                $idArr = explode(',', $notify['class_id']);
                foreach($idArr as $id) {
                    if(in_array($id, $this->rmxUser['classIdArr'])) {
                        $notify['role_change'] = true;
                    }
                }
            }
            // 通知类型
            if($notify['notify_type'] == NOTIFY_TYPE_TEXT) {
                $notify['notify_type'] = '文本通知';
            } else {
                $notify['notify_type'] = '外部链接';
            }
        }
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        // 过滤班级数组
        if($classIdArr) {
            $totalParams['classIdArr'] = $classIdArr;
        }
        // 过滤标题
        if(isset($title)) {
            $totalParams['title'] = $title;
        }
        // 教师权限登录时，只获取任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER && isset($this->rmxUser['classIdArr'])) {
            $totalParams['classIdArr'] = $this->rmxUser['classIdArr'];
        }
        $total = $this->contentModel->get_notify_list($totalParams);
        // 返回值
        exit(admin_table_data($total, $notifyList));   
    }
    // 编辑通知页面
    public function notify_edit($notifyId = 0){
        if(!empty($notifyId)) {
            $this->notifyInfo = $this->contentModel->get_notify_info($notifyId);
            if(trim($this->notifyInfo['imgs'])) {
                $this->notifyInfo['imgArr'] = explode(',', $this->notifyInfo['imgs']);
            }
        }
        $params['isDelete'] = 0;
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['getLevelData'] = true;
        // 教师权限只能发布任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
            $params['classId'] = $this->rmxUser['class_ids'];
        }
        // 只获取行政班
        $params['classType'] = CLASSES_TYPE_NORMAL;

        $this->gradeArray = $this->classesModel->get_grade_class_list($params);

        // 判断是否是管理员
        $isSchoolAdmin = false;
        if($this->rmxUser['user_type'] == USER_TYPE_SCHOOL) {
            $isSchoolAdmin = true;
        } else {
            // 获取学校管理员执教关系
            $this->load->model('staffModel');
            $coachParams['teacherId'] = $this->rmxUser['id'];
            $coachParams['coachType'] = COACH_TYPE_SCHOOL_ADMIN;
            $coachParams['schoolId'] = $this->rmxSchool['id'];
            $coachParams['campusId'] = $this->campusInfo['id'];
            $coachParams['isDelete'] = 0;
            $schoolAdminCoachList = $this->staffModel->get_coach_list($coachParams);
            if($schoolAdminCoachList) {
                $isSchoolAdmin = true;
            }
        }
        $this->isSchoolAdmin = $isSchoolAdmin;

        // 生成又拍云签名
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "notify_edit");
    }
    // 保存通知
    public function save_notify_action(){
        $notifyId = $this->post("id");
        $notifyTitle = $this->post("notify_title");
        $notifyClass = $this->post("notify_class");
        $notifyContent = $this->post("notify_content", false);
        $notifyUrgent = $this->post("notify_urgent");
        $notifyUrgentTime = $this->post("urgent_endtime");
        $materialArr = $this->post('material');
        $notifyType = $this->post('notify_type');
        $externalLink = trim($this->post('external_link'));
        $isTop = $this->post('is_top');
        // 参数检查
        if(!$notifyTitle) throw new Exception("请填写班级通知标题");
        if(!$notifyClass) throw new Exception("请选择班级通知发送班级");
        if($notifyType == NOTIFY_TYPE_TEXT && !$notifyContent) throw new Exception("请填写班级通知内容");
        if($notifyUrgent && !$notifyUrgentTime) throw new Exception("请填写通知截止时间");
        if($materialArr) {
            if(9 < count($materialArr)) {
                throw new Exception("最多只能上传9张图片");
            }
            $material = implode(',', $materialArr);
        } else {
            $material = '';
        }
        // 提示信息
        $msg = $notifyId ? '修改班级通知成功' : '发布班级通知成功';
        if($notifyType == NOTIFY_TYPE_LINK) {
            if(empty($externalLink)) {
                throw new Exception("请填写外部链接地址");
            }
            if(false === strstr($externalLink, 'http://') && false === strstr($externalLink, 'https://')) {
                throw new Exception("链接地址格式错误");
            }
            $notifyContent = '';
            $material = '';
        }
        // 入库
        $data['class_id'] = $notifyClass;
        $data['notify_title'] = $notifyTitle;
        $data['notify_content'] = $notifyContent ? $notifyContent : "";
        $data['notify_urgent'] = $this->post("notify_urgent");
        $data['urgent_endtime'] = $notifyUrgent ? $notifyUrgentTime : "";
        $data['imgs'] = $material;
        $data['notify_type'] = $notifyType;
        $data['external_link'] = $externalLink ? $externalLink : '';
        if($isTop !== "-1") {
            $data['is_top'] = $isTop;
        }

        $data['updatetime'] = date("Y-m-d H:i:s");
        // 操作
        $action = '';
        if($notifyId) {
            $action = 'update';
            $this->db->update(ContentModel::$notifyTable, $data, "id='{$notifyId}'");
        } else {
            $action = 'insert';
            $data['school_id'] = $this->rmxSchool['id'];
            $data['campus_id'] = $this->campusInfo['id'];
            $data['user_id'] = $this->rmxUser['id'];
            $data['createtime'] = $data['updatetime'];
            $this->db->insert(ContentModel::$notifyTable, $data);

            $notifyId = $this->db->insert_id();
        }

        // 如果是紧急通知，需要推送消息到班牌（加上判断紧急通知截止时间）
        $this->load->library('socket');
        if($data['notify_urgent'] && $data['urgent_endtime'] > date('Y-m-d H:i:s')) {
            $this->socket->send_urgent_msg($this->rmxSchool['id'], $notifyClass, $notifyId);
        } else {
            $this->socket->send_notify_msg($this->rmxSchool['id'], $notifyClass, $notifyId);
        }

        // 修改通知不发送模板消息
        if($action == 'insert') {
            // 发布班级，如大于3个，截取前3个班级
            $classNameStr = $this->_get_class_name_str($notifyClass);
            $arr = explode('、', $classNameStr);
            if(count($arr) > 3) {
                $newArr = array_slice($arr, 0, 3);
                $classNameStr = implode('、', $newArr) . '...';
            }
            $data = array(
                'keyword1' => array(
                    'value' => $classNameStr
                ),
                'keyword2' => array(
                    'value' => $this->rmxUser['realname'] ? $this->rmxUser['realname'] : $this->rmxUser['username']
                ),
                'keyword3' => array(
                    'value' => date('Y-m-d H:i:s')
                ),
                // 'keyword4' =>  array(
                //     'value' => $notifyUrgent ? '紧急' : '非紧急'
                // ),
                'keyword4' =>  array(
                    'value' => $notifyTitle
                )
            );
            if($notifyType == NOTIFY_TYPE_TEXT) {
                $url =wx_url('classes/notify_detail/') . $notifyId;
            } else {
                // 跳转外部链接
                $url = $externalLink;
            }

            // 获取学生列表
            $stuParams['isDelete'] = 0;
            $stuParams['schoolId'] = $this->rmxSchool['id'];
            $stuParams['classSet'] = $notifyClass;
            $students = $this->schoolModel->get_student_list($stuParams);
            if($students) {
                $this->load->model('wxUserModel');
                // 截取成100个
                $arr = array_chunk($students, 100);
                foreach($arr as $studentArr) {
                    $processDataArr = array();
                    foreach($studentArr as $student) {
                        array_push($processDataArr, array(
                            'student_id' => $student['id'],
                            'data' => $data 
                        ));
                    }
                    $this->db->insert(WxUserModel::$wxTemplateProcessTable, array(
                        'template_id' => WX_TEMPLATE_NOTIFY,
                        'type' => 'student',
                        'data' => json_encode($processDataArr, JSON_UNESCAPED_UNICODE),
                        'url' => $url,
                        'include_expired' => 1
                    ));
                }
            }

            // 发送模板消息给任课教师
            $this->load->model('staffModel');
            // 获取班级的任课老师
            $coachParams['classSet'] = $notifyClass;
            $coachList = $this->staffModel->get_coach_list($coachParams);
            if($coachList) {
                $teachers = array();
                foreach($coachList as $coach) {
                    if(!in_array($coach['teacher_id'], $teachers)) {
                        array_push($teachers, $coach['teacher_id']);
                    }
                }
                if($teachers) {
                    $this->load->model('wxUserModel');
                    // 截取成100个
                    $arr = array_chunk($teachers, 100);
        
                    foreach($arr as $teacherIdArr) {
                        $processDataArr = array();
                        foreach($teacherIdArr as $teacherId) {
                            // echo'<pre>';var_export($student);exit;
                            array_push($processDataArr, array(
                                'student_id' => $teacherId,
                                'data' => $data 
                            ));
                        }
                        $this->db->insert(WxUserModel::$wxTemplateProcessTable, array(
                            'template_id' => WX_TEMPLATE_NOTIFY,
                            'type' => 'teacher',
                            'data' => json_encode($processDataArr, JSON_UNESCAPED_UNICODE),
                            'url' => $url
                        ));
                    }
                }
            }
        }

        // 返回值
        exit(json($msg, true));
    }

    // 删除通知
    public function delete_notify_action() {
        $id = $this->post('id');
        $data = array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(ContentModel::$notifyTable, $data, array('id' => $id));
        exit(json('删除成功', true));
    }

    // 校园公告
    public function announce(){
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "announce");
    }
    // 编辑校园公告
    public function announce_edit($announceId = 0){
        $this->announceInfo = $this->contentModel->get_announce_info($announceId);
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "announce_edit");
    }
    // 保存校园公告
    public function save_announce_action(){
        $announceId = $this->post("id");
        $announceTitle = $this->post("announce_title");
        $announceContent = $this->post("announce_content", false);
        $announceType = $this->post('announce_type');
        $externalLink = trim($this->post('external_link'));
        $isTop = $this->post("is_top") ? 1 : 0;

        // 参数检查
        if(!$announceTitle) throw new Exception("请填写校园公告标题");


        if($announceType == ANNOUNCE_TYPE_LINK) {
            if(empty($externalLink)) {
                throw new Exception("请填写外部链接地址");
            }
            if(false === strstr($externalLink, 'http://') && false === strstr($externalLink, 'https://')) {
                throw new Exception("链接地址格式错误");
            }
            $notifyContent = '';
        } else {
            if(!$announceContent) throw new Exception("请填写校园公告内容");
            $externalLink = '';
        }

        // 提示信息
        $msg = $announceId ? '修改校园公告成功' : '发布校园公告成功';
        // 入库
        $data['announce_title'] = $announceTitle;
        $data['announce_content'] = $announceContent;
        $data['announce_type'] = $announceType;
        $data['external_link'] = $externalLink;
        $data['updatetime'] = date("Y-m-d H:i:s");
        $data['is_top'] = $isTop;
        // 操作
        $action = '';
        if($announceId) {
            $action = 'update';
            $this->db->update(ContentModel::$announceTable, $data, "id='{$announceId}'");
        } else {
            $action = 'insert';
            $data['school_id'] = $this->rmxSchool['id'];
            $data['campus_id'] = $this->campusInfo['id'];
            $data['user_id'] = $this->rmxUser['id'];
            $data['createtime'] = $data['updatetime'];
            $this->db->insert(ContentModel::$announceTable, $data);

            $announceId = $this->db->insert_id();
        }

        // 修改不发送模板消息
        if($action == 'insert') {
            $data = array(
                'keyword1' => array(
                    'value' => $this->rmxSchool['school_name']
                ),
                'keyword2' => array(
                    'value' => $this->rmxUser['realname'] ? $this->rmxUser['realname'] : $this->rmxUser['username']
                ),
                'keyword3' => array(
                    'value' => date("Y-m-d H:i:s")
                ),
                'keyword4' => array(
                    'value' => $announceTitle
                ),
            );
            if($announceType == ANNOUNCE_TYPE_TEXT) {
                $url =wx_url('classes/announce_detail/') . $announceId;
            } else {
                // 跳转外部链接
                $url = $externalLink;
            }
    
            // 发送模板消息
            // $this->load->library('wxtemplate');
            // $this->wxtemplate->send_template_msg_for_school($this->rmxSchool['id'], WX_TEMPLATE_ANNOUNCE, $data, $url);
            // 后台进程
            $this->load->model('wxUserModel');
            // 发送全校学生
            $params['isDelete'] = 0;
            $params['schoolId'] = $this->rmxSchool['id'];
            $params['field'] = 'id';
            $students = $this->schoolModel->get_student_list($params);
            if($students) {
                $this->load->model('wxUserModel');
                // 截取成100个
                $arr = array_chunk($students, 100);
                // echo'<pre>';var_export($arr);exit;
                foreach($arr as $studentArr) {
                    $processDataArr = array();
                    foreach($studentArr as $student) {
                        // echo'<pre>';var_export($student);exit;
                        array_push($processDataArr, array(
                            'student_id' => $student['id'],
                            'data' => $data 
                        ));
                    }
                    $this->db->insert(WxUserModel::$wxTemplateProcessTable, array(
                        'template_id' => WX_TEMPLATE_ANNOUNCE,
                        'type' => 'student',
                        'data' => json_encode($processDataArr, JSON_UNESCAPED_UNICODE),
                        'url' => $url
                    ));
                }
            }
            // 发送全校教师
            $params['isDelete'] = 0;
            $params['schoolId'] = $this->rmxSchool['id'];
            $params['field'] = 'id';
            $teachers = $this->schoolModel->get_teacher_list($params);
            if($teachers) {
                $this->load->model('wxUserModel');
                // 截取成100个
                $arr = array_chunk($teachers, 100);
                // echo'<pre>';var_export($arr);exit;
                foreach($arr as $teacherArr) {
                    $processDataArr = array();
                    foreach($teacherArr as $teacher) {
                        // echo'<pre>';var_export($student);exit;
                        array_push($processDataArr, array(
                            'student_id' => $teacher['id'],
                            'data' => $data 
                        ));
                    }
                    $this->db->insert(WxUserModel::$wxTemplateProcessTable, array(
                        'template_id' => WX_TEMPLATE_ANNOUNCE,
                        'type' => 'teacher',
                        'data' => json_encode($processDataArr, JSON_UNESCAPED_UNICODE),
                        'url' => $url
                    ));
                }
            }
        }

        // 发送socket
        $classParams['schoolId'] = $this->rmxSchool['id'];
        $classParams['campusId'] = $this->campusInfo['id'];
        $classParams['isDelete'] = 0;
        // 获取全校班级id
        $classArr = $this->classesModel->get_class_list($classParams);
        if($classArr) {
            $classIdArr = array();
            foreach($classArr as $class) {
                array_push($classIdArr, $class['id']);
            }
            $classIdSet = implode(',', $classIdArr);
            $this->load->library('socket');
            $this->socket->send_announce_msg($this->rmxSchool['id'], $classIdSet, $announceId);
        }

        // 返回值
        exit(json($msg, true));
    }
    // ajax获取校园公告列表
    public function get_announce_list() {
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campus_id'] = $this->campusInfo['id'];
        $total = $this->contentModel->get_announce_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campus_id'] = $this->campusInfo['id'];
        // 过滤软删除
        $data['isDelete'] = 0;
        $announceList = $this->contentModel->get_announce_list($data);
        foreach($announceList as & $announce) {
            // 判断当前用户有没编辑权限
            $announce['role_change'] = true;
            if($this->rmxUser['user_type'] == USER_TYPE_TEACHER && $this->rmxUser['id'] != $announce['user_id'] ) {
                $announce['role_change'] = false;
            }
            // 通知类型
            if($announce['announce_type'] == ANNOUNCE_TYPE_TEXT) {
                $announce['announce_type'] = '文本公告';
            } else {
                $announce['announce_type'] = '外部链接';
            }
        }

        // 返回值
        exit(admin_table_data($total, $announceList));   
    }

    // 删除公告
    public function delete_announce_action() {
        $id = $this->post('id');
        $data = array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(ContentModel::$announceTable, $data, array('id' => $id));
        exit(json('删除成功', true));
    }

    // 课程表
    public function schedule(){
        // 获取年级
        $gradeParams['schoolId'] = $this->rmxSchool['id'];
        $gradeParams['campusId'] = $this->campusInfo['id'];
        $gradeParams['isDelete'] = 0;
        $this->gradeList = $this->classesModel->get_grade_list($gradeParams);
        // 获取该学校课程模板
        $scheduleParams['schoolId'] = $this->rmxSchool['id'];
        // 课程暂不区分校区
        // 区分校区
        $scheduleParams['campusId'] = $this->campusInfo['id'];
        $scheduleParams['isThisWeek'] = 1;
        $scheduleParams['isDelete'] = 0;
        $this->schedule = $this->classesModel->get_school_schedule_row($scheduleParams);
        // 生成又拍云签名,用于上传导入的课表
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);

        // // 判断是否年级不同作息（存在grade_id=0即是全校统一）
        // $onlyOneScheduleParams['isDelete'] = 0;
        // $onlyOneScheduleParams['schoolId'] = $this->rmxSchool['id'];
        // $onlyOneScheduleParams['campusId'] = $this->campusInfo['id'];
        // $onlyOneScheduleParams['gradeId'] = 0;
        // $this->onlyOneSchedule = $this->classesModel->get_school_schedule($onlyOneScheduleParams) ? true : false;
        // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
        $this->onlyOneSchedule = $this->classesModel->check_is_only_one_schedule($this->rmxSchool['id'], $this->campusInfo['id']);

        // 判断是否存在教学班
        $teachingClassParams['schoolId'] = $this->rmxSchool['id'];
        $teachingClassParams['campusId'] = $this->campusInfo['id'];
        $teachingClassParams['classType'] = CLASSES_TYPE_TEACHING;
        $teachingClassParams['getRowNumber'] = 1;
        $teachingClassParams['isDelete'] = 0;
        $teachingClassNum = $this->classesModel->get_class_list($teachingClassParams);
        // echo '<pre>';var_export($teachingClassNum);exit;
        if($teachingClassNum > 0) {
            $this->existTeachingClass = true;
        } else {
            $this->existTeachingClass = false;
        }

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "schedule");
    }
    // 获取课程表页面的班级列表
    public function get_schedule_class_list(){
        // 教师权限登录时，只获取任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
            $totalParams['classId'] = $data['classId'] = $this->rmxUser['class_ids'];
        }

        // 班级id筛选
        if($this->get("gradeId")) $totalParams['gradeId'] = $data['gradeId'] = $this->get("gradeId");
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        $total = $this->classesModel->get_class_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $data['isDelete'] = 0;
        $classList = $this->classesModel->get_class_list($data);
        // 获取学校课表数据
        $scheduleLessonParams['schoolId'] = $this->rmxSchool['id'];
        $scheduleLessonParams['campusId'] = $this->campusInfo['id'];
        $scheduleLessonParams['isDelete'] = 0;
        $scheduleLessonList = $this->classesModel->get_school_schedule_lesson_fast($scheduleLessonParams);
        // 使用class_id作为键值
        $scheduleLessonList = array_value_to_key($scheduleLessonList, 'class_id');
        // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
        $onlyOneSchedule = $this->classesModel->check_is_only_one_schedule($this->rmxSchool['id'], $this->campusInfo['id']);
        if($onlyOneSchedule) {
            // 全校作息
            $schoolScheduleParams['schoolId'] = $this->rmxSchool['id'];
            $schoolScheduleParams['campusId'] = $this->campusInfo['id'];
            $schoolScheduleParams['gradeId'] = 0;
            $schoolScheduleParams['isDelete'] = 0;
            $scheduleList = $this->classesModel->get_school_schedule($schoolScheduleParams);
            $scheduleInfo =  $scheduleList ? $scheduleList[0] : array();
        } else {
            // 年级不同作息，获取作息列表
            $schoolScheduleParams['schoolId'] = $this->rmxSchool['id'];
            $schoolScheduleParams['campusId'] = $this->campusInfo['id'];
            $schoolScheduleParams['isDelete'] = 0;
            $scheduleList = $this->classesModel->get_school_schedule($schoolScheduleParams);
            $scheduleList = array_value_to_key($scheduleList, 'grade_id');
        }
        // 获取作息
        foreach($classList as &$class) {
            $class['className'] = $class['class_name'];
            // 判断是否有班级课表
            if(isset($scheduleLessonList[$class['id']])) {
                $class['hasScheduleLesson'] = 1;
            } else {
                $class['hasScheduleLesson'] = 0;
            }
            if($onlyOneSchedule) {
                // 全校作息
                $class['scheduleId'] = $scheduleInfo ? $scheduleInfo['id'] : '';
            } else {
                // 年级不同作息
                $gradeSchdeuleId = 0;
                if(isset($scheduleList[$class['grade_id']])) {
                    $gradeSchdeuleId = $scheduleList[$class['grade_id']]['id'];
                }
                $class['scheduleId'] = $gradeSchdeuleId;
            }
        }
        // echo '<pre>';var_export($classList);exit;
        // 返回值
        exit(admin_table_data($total, $classList));   
    }
    // 显示课程表页面
    public function schedule_table($classId){
        $this->classInfo = $this->classesModel->get_class_info($classId);
        $this->thisWeek = $this->nextWeek = array();

        // 获取本校全部老师
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $teacherList = $this->schoolModel->get_teacher_list($params);
        $teacherList = array_value_to_key($teacherList, 'id');
        // 获取本校全部课室
        $roomParams['schoolId'] = $this->rmxSchool['id'];
        $roomParams['isDelete'] = 0;
        $roomList = $this->classesModel->get_classroom_list($roomParams);
        $roomList = array_value_to_key($roomList, 'id');

        // 获取课程表数据
        // $params['schoolId'] = $this->rmxSchool['id'];
        // $params['campusId'] = $this->campusInfo['id'];
        // $this->schedule = $schedule = $this->classesModel->get_school_schedule($params);
        // foreach($schedule as $item) {
        //     $scheduleData = $item;
        //     // 获取课程
        //     $lessonParams['scheduleId'] = $item['id'];
        //     $lessonParams['classId'] = $classId;
        //     $lessonList = $this->classesModel->get_school_schedule_lesson($lessonParams);
        //     foreach($lessonList as $lesson) {
        //         // 获取教师名称
        //         $lesson['teacherName'] = isset($teacherList[$lesson['schedule_teacher']]) ? $teacherList[$lesson['schedule_teacher']]['realname'] : '';
        //         // 获取教室名称
        //         $lesson['roomName'] = isset($roomList[$lesson['schedule_room_id']]) ? $roomList[$lesson['schedule_room_id']]['classroom_name'] : '';
        //         // 将课程放入数组
        //         $scheduleData['lesson'][$lesson['schedule_week_index']. $lesson['schedule_class_index']] = $lesson;
        //     }
        //     // 判断是本周还是下周
        //     if($item['schedule_this_week']) {
        //         $this->thisWeek = $scheduleData;
        //     } else {
        //         $this->nextWeek = $scheduleData;
        //     }
        // }

        // 更改逻辑--by yzh
        $schduleThisWeek = $this->classesModel->get_schedule_by_class($this->classInfo['school_id'], $this->classInfo['grade_id']);
        if(empty($schduleThisWeek)) {
            // 学校统一作息
            $schduleThisWeek = $this->classesModel->get_schedule_by_class($this->classInfo['school_id'], 0);
        }
        // 兼容功能课室
        if($this->classInfo['is_functional']) {
            // 获取课室
            if($this->classInfo['classroom_id']) {
                // 获取在这个课室上课的课程
                $schduleThisWeek = $this->classesModel->get_schedule_by_classroom($this->classInfo['classroom_id'], 1);
                // echo '<pre>';var_export($schduleThisWeek);exit;
            }
        }
        // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
        $onlyOneSchedule = $this->classesModel->check_is_only_one_schedule($this->rmxSchool['id'], $this->campusInfo['id']);
        if(!empty($schduleThisWeek)){
            // 获取课程
            $lessonParams['isDelete'] = 0;
            $lessonParams['schoolId'] =  $this->rmxSchool['id'];

            // if($onlyOneSchedule) {
            //     // 年级不同作息，不需要判断scheduleid
            //     $lessonParams['scheduleId'] = $schduleThisWeek['id'];
            // }
            // 年级不同作息，不需要判断scheduleid
            $lessonParams['scheduleId'] = $schduleThisWeek['id'];

            // 兼容功能课室
            if($this->classInfo['is_functional']) {
                $lessonParams['classroom'] = $this->classInfo['classroom_id'];
            } else {
                $lessonParams['classId'] = $classId;
            }

            $lessonList = $this->classesModel->get_school_schedule_lesson($lessonParams);
            foreach($lessonList as $key => $lesson) {
                // 如果是行政班，过滤不是在本课室上课的课程
                if($this->classInfo['class_type'] == CLASSES_TYPE_NORMAL) {
                    if($this->classInfo['classroom_id'] != $lesson['schedule_room_id']) {
                        unset($lessonList[$key]);
                        continue;
                    }
                }

                // 获取教师名称
                // $lesson['teacherName'] = isset($teacherList[$lesson['schedule_teacher']]) ? $teacherList[$lesson['schedule_teacher']]['realname'] : '';
                // 支持多个授课老师
                $scheduleTeacherIdArr = explode(',', $lesson['schedule_teacher']);
                $scheduleTeacherNameArr = array();
                foreach($scheduleTeacherIdArr as $scheduleTeacherId) {
                    if(isset($teacherList[$scheduleTeacherId])) {
                        array_push($scheduleTeacherNameArr, $teacherList[$scheduleTeacherId]['realname']);
                    }
                }
                $lesson['teacherName'] = implode('，', $scheduleTeacherNameArr);

                // 获取教室名称
                $lesson['roomName'] = isset($roomList[$lesson['schedule_room_id']]) ? $roomList[$lesson['schedule_room_id']]['classroom_name'] : '';
                // 将课程放入数组
                $schduleThisWeek['lesson'][$lesson['schedule_week_index']. $lesson['schedule_class_index']] = $lesson;
            }
            $this->thisWeek = $schduleThisWeek;
        }

        // echo '<pre>';var_export($lessonList);exit;
        // if(!empty($schduleNextWeek)){
        //     // 获取课程
        //     $lessonParams['isDelete'] = 0;
        //     $lessonParams['schoolId'] =  $this->rmxSchool['id'];
        //     $lessonParams['scheduleId'] = $schduleNextWeek['id'];
        //     $lessonParams['classId'] = $classId;
        //     $lessonList = $this->classesModel->get_school_schedule_lesson($lessonParams);
        //     foreach($lessonList as $lesson) {
        //         // 获取教师名称
        //         $lesson['teacherName'] = isset($teacherList[$lesson['schedule_teacher']]) ? $teacherList[$lesson['schedule_teacher']]['realname'] : '';
        //         // 获取教室名称
        //         $lesson['roomName'] = isset($roomList[$lesson['schedule_room_id']]) ? $roomList[$lesson['schedule_room_id']]['classroom_name'] : '';
        //         // 将课程放入数组
        //         $schduleNextWeek['lesson'][$lesson['schedule_week_index']. $lesson['schedule_class_index']] = $lesson;
        //     }
        //     $this->nextWeek = $schduleNextWeek;
        // }

        // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
        if($onlyOneSchedule) {
            $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "schedule_table"); 
        } else {
            // 课时数组
            $periodArr = array();
            if($schduleThisWeek) {
                $earlyMorningNum = $schduleThisWeek['schedule_early_morning_number'];
                $nightNum = $schduleThisWeek['schedule_night_number'];
                $lessonNum = $schduleThisWeek['schedule_morning_number'] + $schduleThisWeek['schedule_afternoon_number'];
                for($i = 1; $i <= $earlyMorningNum; $i ++) {
                    $periodArr[] = '早间' . $i;
                }
                for($i = 1; $i <= $lessonNum; $i ++) {
                    $periodArr[] = '第' . $i . '节';
                }
                for($i = 1; $i <= $nightNum; $i ++) {
                    $periodArr[] = '晚间' . $i;
                }
            }
            $this->periodArr = $periodArr;

            // 获取年级作息列表
            $gradeScheduleList = $this->classesModel->get_one_daily_grade_schdedule($this->rmxSchool['id'], $this->campusInfo['id'], $this->classInfo['grade_id']);
            // 获取作息
            foreach($gradeScheduleList as &$item) {
                $timeArr = json_decode($item['schedule_time_json'], true);
                $item['timeArr'] = $timeArr;
            }

            
            $this->gradeScheduleList = $gradeScheduleList;
            $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "schedule_table_grade"); 
        }
    }

    // 班级相册
    public function album(){
        // 获取年级
        $gradeParams['schoolId'] = $this->rmxSchool['id'];
        $gradeParams['campusId'] = $this->campusInfo['id'];
        $gradeParams['isDelete'] = 0;
        $this->gradeList = $this->classesModel->get_grade_list($gradeParams);
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "album");
    }
    // 获取相册页面的班级列表
    public function get_album_class_list(){
        // // 暂可获取行政班级
        // // 只获取行政班级
        // $totalParams['classType'] = $data['classType'] = CLASSES_TYPE_NORMAL;

        // 教师权限只能发布任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
            $totalParams['classId'] = $data['classId'] = $this->rmxUser['class_ids'];
        }
        // 班级id筛选
        if($this->get("gradeId")) $totalParams['gradeId'] = $data['gradeId'] = $this->get("gradeId");
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        $total = $this->classesModel->get_class_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $data['isDelete'] = 0;
        $classList = $this->classesModel->get_class_list($data);
        foreach($classList as &$class) {
            $class['className'] = $class['class_name'];
        }
        // 返回值
        exit(admin_table_data($total, $classList));   
    }
    // 显示相册页面
    public function album_list($classId){
        $this->classId = $classId;
        // 获取相册分类
        $params['classId'] = $classId;
        $this->albumCategory = $albumCategory = $this->contentModel->get_album_category($params);
        // 获取相册内容
        foreach($this->albumCategory as &$category) {
            // 获取相册内容
            $albumParams['categoryId'] = $category['id'];
            $category['album'] = $this->contentModel->get_album($albumParams);
        }
        // 生成又拍云签名
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);
        
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "album_list");
    }
    // 保存相册分类
    public function save_category_action(){
        $categoryId = $this->post("id");
        $classId = $this->post("class_id");
        $categoryName = $this->post("category_name");

        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($classId);
        if($classInfo['school_id'] != $this->rmxSchool['id']) throw new Exception("参数错误，提交失败");
        // 参数检查
        if(!$categoryName) throw new Exception("请填写相册分类名称");
        // 入库
        $data['album_category_name'] = $categoryName;
        $data['updatetime'] = date("Y-m-d H:i:s");
        if($categoryId) {
            $this->db->update(ContentModel::$albumCategoryTable, $data, "id='{$categoryId}'");
        } else {
            $data['school_id'] = $this->rmxSchool['id'];
            $data['campus_id'] = $this->campusInfo['id'];
            $data['class_id'] = $classId;
            $data['createtime'] = $data['updatetime'];
            $this->db->insert(ContentModel::$albumCategoryTable, $data);
        }
        // 返回值
        $msg = $categoryId ? '修改相册分类成功' : '新增相册分类成功';
        exit(json($msg, true));
    }
    // 保存相册图片
    public function save_image_action(){
        $imageId = $this->post('id');
        $classId = $this->post("class_id");
        $categoryId = $this->post("category_id");
        $imageLink = $this->post("image_link");
        $imageTitle = $this->post("image_title") ? $this->post("image_title") : '';
        // 参数检查
        if(!$classId || !$categoryId) throw new Exception("参数错误");
        // if(!$imageTitle) throw new Exception("请填写图片标题");
        if(!$imageLink) throw new Exception("请上传图片");
        // 入库
        $data['image_link'] = $imageLink;
        $data['image_desc'] = $imageTitle;
        $data['image_recommend'] = $this->post("image_recommend");
        $data['image_sort'] = $this->post("image_sort");
        $data['updatetime'] = date("Y-m-d H:i:s");
        if($imageId) {
            $this->db->update(ContentModel::$albumTable, $data, "id='{$imageId}'");
        } else {
            $data['school_id'] = $this->rmxSchool['id'];
            $data['campus_id'] = $this->campusInfo['id'];
            $data['class_id'] = $classId;
            $data['category_id'] = $categoryId;
            $data['createtime'] = $data['updatetime'];
            // 多图上传
            $linkArr = explode(',', $imageLink);
            foreach($linkArr as $link) {
                $data['image_link'] = $link;
                $data['image_recommend'] = $this->post("image_recommend");
                $data['image_sort'] = 0;
                $this->db->insert(ContentModel::$albumTable, $data);
            }
        }
        // 返回值
        $msg = $imageId ? '修改图片成功' : '新增图片成功';
        exit(json($msg, true));
    }
    // 删除相册图片
    public function delete_album_image(){
        $imageId = $this->post("id");
        $imageInfo = $this->contentModel->get_album_image_info($imageId);
        if(!$imageInfo || $imageInfo['school_id'] != $this->rmxSchool['id']) throw new Exception("删除失败，请刷新后重试");
        // 删除图片
        // $this->db->delete(ContentModel::$albumTable, "`id`='{$imageId}'");
        $this->db->update(ContentModel::$albumTable, array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        ), "`id`='{$imageId}'");
        exit(json("删除成功", true));
    }
    // 删除相册分类
    public function delete_album_category(){
        $categoryId = $this->post("id");
        $categoryInfo = $this->contentModel->get_album_category_info($categoryId);
        if(!$categoryInfo || $categoryInfo['school_id'] != $this->rmxSchool['id']) throw new Exception("删除失败，请刷新后重试");
        // 删除图片
        // $this->db->delete(ContentModel::$albumTable, "`category_id`='{$categoryId}'");
        $this->db->update(ContentModel::$albumTable, array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        ), "`category_id`='{$categoryId}'");
        // 删除分类
        // $this->db->delete(ContentModel::$albumCategoryTable, "`id`='{$categoryId}'");
        $this->db->update(ContentModel::$albumCategoryTable, array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        ), "`id`='{$categoryId}'");
        exit(json("删除成功", true));
    }

    // 管理员发布班级相册列表
    public function album_list_by_admin(){
        // 是否学校管理员
        $isSchoolAdmin = false;
        if($this->rmxUser['user_type'] == USER_TYPE_SCHOOL) {
            $isSchoolAdmin = true;
        }
        // 获取执教关系列表
        $coachParams['teacherId'] = $this->rmxUser['id'];
        $this->load->model('staffModel');
        $coachList = $this->staffModel->get_coach_list($coachParams);
        if($this->checkIsSchoolAdminByCoachList($coachList)) {
            $isSchoolAdmin = true;
        }
        $this->isSchoolAdmin = $isSchoolAdmin;
        // 获取年级
        $gradeParams['schoolId'] = $this->rmxSchool['id'];
        $gradeParams['campusId'] = $this->campusInfo['id'];
        $gradeParams['isDelete'] = 0;
        $this->gradeList = $this->classesModel->get_grade_list($gradeParams);
        // 获取班级列表
        $classData = $this->classesModel->get_class_list($gradeParams);
        $classArray = array();
        foreach($classData as $class) {
            $classArray[$class['grade_id']][] = array(
                "id" => $class['id'],
                "name" => $class['class_name']
            );
        }
        $this->classList = json_encode($classArray);
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "album_list_by_admin");
    }
    public function get_category_by_admin_list(){
         // 筛选班级
         if($this->get('class_id') && 0 !== $this->get('class_id')) {
            $classId = $this->get('class_id');
            $totalParams['classId'] = $cateByAdminParams['classId'] = $classId;
        }
        // 搜索标题
        if($this->get('title') && '' !== trim($this->get('title'))) {
            $title = trim($this->get('title'));
            $totalParams['title'] = $cateByAdminParams['title'] = $title;
        }
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        $total = $this->contentModel->get_album_category_by_admin_list($totalParams);

        // 获取管理员相册
        $cateByAdminParams['pageStart'] = $this->get('start');
        $cateByAdminParams['pageSize']= $this->get("length");
        $cateByAdminParams['schoolId'] = $this->rmxSchool['id'];
        $cateByAdminParams['campusId'] = $this->campusInfo['id'];
        $cateByAdminList = $this->contentModel->get_album_category_by_admin_list($cateByAdminParams);
        foreach($cateByAdminList as &$video) {
            // 查询视频发送班级
            $params['classId'] = $video['class_ids'];
            // 过滤软删除
            $params['isDelete'] = 0;
            $video['classList'] = $this->classesModel->get_grade_class_list($params);
           
        }
        // echo'<pre>';var_export($cateByAdminList);exit;
        exit(admin_table_data($total, $cateByAdminList));
    }
    // 管理员发布班级相册发布
    public function album_by_admin_edit($cateByAdminId = 0){
        $cateInfo = array();
        $cateByAdminInfo = array();
        $imgArr = array();

        if($cateByAdminId) {
            $cateByAdminInfo = $this->contentModel->get_album_category_by_admin_info($cateByAdminId);
            $imgArr = json_decode($cateByAdminInfo['imgs'], true);
            // // 获取分类
            // $cateParams['categoryByAdminId'] = $cateByAdminId;
            // $cateList = $this->contentModel->get_album_category($cateParams);
            // if($cateList) {
            //     $cateInfo = $cateList[0];
            // }
        }
      
        // 年级班级列表
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['getLevelData'] = true;
        // 过滤软删除
        $params['isDelete'] = 0;
        $this->gradeArray = $this->classesModel->get_grade_class_list($params);
        // 生成又拍云签名
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);

        $this->cateByAdminInfo = $cateByAdminInfo;
        // $this->cateInfo = $cateInfo;
        $this->imgArr = $imgArr;
        
        // echo'<pre>';var_export($imgArr);exit;
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "album_by_admin_edit");
    }
    // 保存管理员相册分类和相册
    public function save_album_by_admin_action(){
        $postCategoryByAdminId = $this->post("id");
        $title = $this->post("title");
        $albumClass = $this->post("class_ids");
        $imageArr = $this->post("img_arr");
      
        // 参数检查
        if(!$title) throw new Exception("请填写相册标题");
        // 参数检查
        if(!$albumClass) throw new Exception("请选择发布班级");
        $albumClassIdArr = explode(',', $albumClass);
        if(empty($imageArr)) {
            throw new Exception("请上传图片");
        }
        $imgs = json_encode($imageArr, true);
     
        // 入库
        $cateByAdminData['school_id'] = $this->rmxSchool['id'];
        $cateByAdminData['campus_id'] = $this->campusInfo['id'];
        $cateByAdminData['class_ids'] = $albumClass; // 班级id为0
        $cateByAdminData['title'] = $title;
        $cateByAdminData['imgs'] = $imgs;
        $cateByAdminData['updatetime'] = date("Y-m-d H:i:s");
        if($postCategoryByAdminId) {
            $this->db->update(ContentModel::$albumCategoryByAdminTable, $cateByAdminData, "id='{$postCategoryByAdminId}'");
            $categoryByAdminId = $postCategoryByAdminId;
        } else {
            $cateByAdminData['createtime'] = $cateByAdminData['updatetime'];
            $this->db->insert(ContentModel::$albumCategoryByAdminTable, $cateByAdminData);
            $categoryByAdminId = $this->db->insert_id();
        }

        // 获取分类
        $cateParams['categoryByAdminId'] = $categoryByAdminId;
        $cateList = $this->contentModel->get_album_category($cateParams);
        // echo'<pre>';var_export($categoryByAdminId);exit;
        $cateData['school_id'] = $this->rmxSchool['id'];
        $cateData['campus_id'] = $this->campusInfo['id'];
        $cateData['class_id'] = 0; // 班级id为0
        $cateData['album_category_name'] = $title;
        $cateData['cate_by_admin_id'] = $categoryByAdminId;
        $cateData['updatetime'] = date("Y-m-d H:i:s");
        if(!empty($cateList)) {
            // 更新分类
            $cateId = $cateList[0]['id'];
            $this->db->update(ContentModel::$albumCategoryTable, $cateData, "id='{$cateId}'");
        } else {
            // 新增分类
            $cateData['createtime'] = $cateData['updatetime'];
            $this->db->insert(ContentModel::$albumCategoryTable, $cateData);
            $cateId = $this->db->insert_id();
        }

        // 获取该分类的所有相册，包括已删除
        $cateAlbumParams['includeDelete'] = 0;
        $cateAlbumParams['categoryId'] = $cateId;
        $cateAlbumList = $this->contentModel->get_album($cateAlbumParams);
        $cateAlbumList = array_value_to_key_with_underline($cateAlbumList, 'class_id,image_link');
       
        // 先删除该分类的所有相册
        $deleteAlbumData = array(
            'is_delete' => 1,
            'updatetime' => date("Y-m-d H:i:s"),
        );
        $this->db->update(ContentModel::$albumTable, $deleteAlbumData, "category_id='{$cateId}'");

        // 处理相册数据
        $imgData['school_id'] = $this->rmxSchool['id'];
        $imgData['campus_id'] = $this->campusInfo['id'];
        $imgData['category_id'] = $cateId;
        $imgData['image_desc'] = $title;
        $imgData['image_sort'] = 1; // 默认排序靠前
        $imgData['is_delete'] = 0;
        $imgData['updatetime'] = date("Y-m-d H:i:s");
        foreach($albumClassIdArr as $albumClassId) {
            $imgData['class_id'] = $albumClassId;
            // 多图上传
            foreach($imageArr as $item) {
                $imgData['image_link'] = $item['src'];
                $imgData['image_recommend'] = $item['recommend'];
                $albumKey = $albumClassId . '_' . $item['src'];
                if(isset($cateAlbumList[$albumKey])) {
                    // 更新相册
                    $albumId = $cateAlbumList[$albumKey]['id'];
                    $this->db->update(ContentModel::$albumTable, $imgData, "id='{$albumId}'");
                } else {
                    // 新增相册
                    $imgData['createtime'] = $imgData['updatetime'];
                    $this->db->insert(ContentModel::$albumTable, $imgData);
                }
            }
        }
        // echo '<pre>';var_export($imgData);exit;
        // 返回值
        $msg = $postCategoryByAdminId ? '修改相册成功' : '新增相册成功';
        exit(json($msg, true));
    }
    // 删除管理员相册分类和相册
    public function delete_album_by_admin_action() {
        $albumCategoryByAdminId = $this->post('id');
        $delData = array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(ContentModel::$albumCategoryByAdminTable, $delData, array('id' => $albumCategoryByAdminId));
        // 删除相册分类
        // 获取分类
        $cateParams['categoryByAdminId'] = $albumCategoryByAdminId;
        $cateList = $this->contentModel->get_album_category($cateParams);
        if($cateList) {
            $cateId = $cateList[0]['id'];
            $this->db->update(ContentModel::$albumCategoryTable, $delData, array('id' => $cateId));
            // 删除相册
            $this->db->update(ContentModel::$albumTable, $delData, array('category_id' => $cateId));
        }

        exit(json('删除成功', true));
    }

    // 班级视频
    public function video(){
        // 获取年级
        $gradeParams['schoolId'] = $this->rmxSchool['id'];
        $gradeParams['campusId'] = $this->campusInfo['id'];
        $gradeParams['isDelete'] = 0;
        $this->gradeList = $this->classesModel->get_grade_list($gradeParams);
        // 获取班级列表
        $classData = $this->classesModel->get_class_list($gradeParams);
        $classArray = array();
        foreach($classData as $class) {
            $classArray[$class['grade_id']][] = array(
                "id" => $class['id'],
                "name" => $class['class_name']
            );
        }
        $this->classList = json_encode($classArray);

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "video");
    }
    // ajax获取班级视频班级列表
    // public function get_video_class_list(){
    //     // 班级id筛选
    //     if($this->get("gradeId")) $totalParams['gradeId'] = $data['gradeId'] = $this->get("gradeId");
    //     // 获取数据条数
    //     $totalParams['getRowNumber'] = true;
    //     $totalParams['campusId'] = $this->campusInfo['id'];
    //     $totalParams['schoolId'] = $this->rmxSchool['id'];
    //     // 过滤软删除
    //     $totalParams['isDelete'] = 0;
    //     $total = $this->classesModel->get_class_list($totalParams);
    //     // 获取数据
    //     $data['pageStart'] = $this->get('start');
    //     $data['pageSize']= $this->get("length");
    //     $data['schoolId'] = $this->rmxSchool['id'];
    //     $data['campusId'] = $this->campusInfo['id'];
    //     // 过滤软删除
    //     $data['isDelete'] = 0;
    //     $classList = $this->classesModel->get_class_list($data);
    //     foreach($classList as &$class) {
    //         $class['className'] = $class['class_name'];
    //     }
    //     // 返回值
    //     exit(admin_table_data($total, $classList));   
    // }
    // 班级视频列表
    public function video_list($classId){
        $this->classInfo = $classInfo = $this->classesModel->get_class_info($classId);
        if(!$classInfo || $classInfo['school_id'] != $this->rmxSchool['id'])show_error("参数不错，班级不存在");

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "video_list");
    }
    // ajax获取班级视频列表
    public function get_video_list() {
        // 默认获取当前校区的所有班级
        $classIdArr = $this->_get_campus_class_id_Arr();
        // 筛选班级
        if($this->get('class_id') && 0 !== $this->get('class_id')) {
            $classId = $this->get('class_id');
            $data['classId'] = $classId;
            $totalParams['classId'] = $classId;
        }
        // 搜索标题
        if($this->get('title') && '' !== trim($this->get('title'))) {
            $title = trim($this->get('title'));
        }
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        // 过滤软删除
        $data['isDelete'] = 0;
        // 过滤班级数组
        if($classIdArr) {
            $data['classIdArr'] = $classIdArr;
        }
        // 过滤标题
        if(isset($title)) {
            $data['title'] = $title;
        }
        // 教师权限登录时，只获取任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER && isset($this->rmxUser['classIdArr'])) {
            $data['classIdArr'] = $this->rmxUser['classIdArr'];
        }
        $videoList = $this->contentModel->get_video_list($data);
        foreach($videoList as &$video) {
            // 查询视频发送班级
            $params['classId'] = $video['class_id'];
            // 过滤软删除
            $params['isDelete'] = 0;
            $video['classList'] = $this->classesModel->get_grade_class_list($params);
            // 判断当前用户有没编辑权限
            $video['role_change'] = true;
            if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
                $video['role_change'] = false;
                $idArr = explode(',', $video['class_id']);
                foreach($idArr as $id) {
                    if(in_array($id, $this->rmxUser['classIdArr'])) {
                        $video['role_change'] = true;
                    }
                }
            }
        }
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        // 过滤班级数组
        if($classIdArr) {
            $totalParams['classIdArr'] = $classIdArr;
        }
        // 过滤标题
        if(isset($title)) {
            $totalParams['title'] = $title;
        }
        // 教师权限登录时，只获取任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER && isset($this->rmxUser['classIdArr'])) {
            $totalParams['classIdArr'] = $this->rmxUser['classIdArr'];
        }
        $total = $this->contentModel->get_video_list($totalParams);
        // 返回值
        exit(admin_table_data($total, $videoList));   
    }
    // 编辑班级视频页面
    public function video_edit($videoId = 0){
        if(!empty($videoId)) {
            $this->videoInfo = $this->contentModel->get_video_info($videoId);
            // 检查视频文件是否存在
            $fileExits = check_remote_file_exists($this->videoInfo['video_link']);
            if(!$fileExits) $this->videoInfo['video_link'] =  str_replace(UP_VIDEO_NEW_NAME, "", $this->videoInfo['video_link']);
        }
        // 年级班级列表
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['getLevelData'] = true;
        // 教师权限只能发布任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
            $params['classId'] = $this->rmxUser['class_ids'];
        }
        // 过滤软删除
        $params['isDelete'] = 0;
        // // 暂不只获取行政班
        // // 只获取行政班
        // $params['classType'] = CLASSES_TYPE_NORMAL;

        $this->gradeArray = $this->classesModel->get_grade_class_list($params);
        // 生成又拍云签名
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        // 通知地址
        $notifyUrl = web_url('delete_upyun_file', 'api');
        $serviceParams = $serviceConfig->getVideoUploadParams(UP_FILEPATH, $this->policy, $this->signature, $notifyUrl);

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "video_edit");
    }
    // 保存班级视频
    public function save_video_action(){
        $videoId = $this->post("id");
        $videoTitle = $this->post("video_title");
        $videoClass = $this->post("video_class");
        $videoFile = $this->post("video_link");
        // $playInClassMode = $this->post("play_in_class_mode") ? $this->post("play_in_class_mode") : 0;

        // 参数检查
        if(!$videoTitle) throw new Exception("请填写班级视频标题");
        if(!$videoClass) throw new Exception("请选择班级视频发送班级");
        if(!$videoFile) throw new Exception("请上传班级视频");
        // 入库
        $data['class_id'] = $videoClass;
        $data['video_title'] = $videoTitle;
        // 视频地址
        $videoFile = str_replace(UP_VIDEO_NEW_NAME, "", $videoFile);
        $data['video_link'] = str_replace(".mp4", UP_VIDEO_NEW_NAME. ".mp4", $videoFile);
        $data['video_poster'] = $this->post("video_poster");
        // $data['play_in_class_mode'] = $playInClassMode;
        $data['updatetime'] = date("Y-m-d H:i:s");

        // 视频截取封面
        if(empty($data['video_poster'])) {
            // 加载又拍云sdk
            require_once('vendor/autoload.php');
            // 初始化又拍云接口
            $config = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
            $upyun = new Upyun\Upyun($config);
            $videoUrl = str_replace(UP_URL, '', $videoFile);
            $videoCover = date("Y") . "/" . date("m") . "/" . date("d"). "/". uniqid() . '.jpg';
            $result = $upyun->snapshot($videoUrl, $videoCover, '00:00:01');
            $data['video_poster'] = UP_URL . $result['save_as'];
        }

        if($videoId) {
            $this->db->update(ContentModel::$videoTable, $data, "id='{$videoId}'");
        } else {
            $data['school_id'] = $this->rmxSchool['id'];
            $data['campus_id'] = $this->campusInfo['id'];
            $data['user_id'] = $this->rmxUser['id'];
            $data['createtime'] = $data['updatetime'];
            $this->db->insert(ContentModel::$videoTable, $data);
        }
        // 返回值
        $msg = $videoId ? '修改班级视频成功' : '发布班级视频成功';
        exit(json($msg, true));
    }
    // 删除班级视频
    public function delete_video_action() {
        $id = $this->post('id');
        $data = array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(ContentModel::$videoTable, $data, array('id' => $id));
        exit(json('删除成功', true));
    }
    // 班级荣誉
    public function honor(){
        // 获取年级
        $gradeParams['schoolId'] = $this->rmxSchool['id'];
        $gradeParams['campusId'] = $this->campusInfo['id'];
        $gradeParams['isDelete'] = 0;
        $this->gradeList = $this->classesModel->get_grade_list($gradeParams);
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "honor");
    }
    // 获取班级荣誉页面的班级列表
    public function get_honor_class_list(){
        // 教师权限只能发布任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
            $totalParams['classId'] = $data['classId'] = $this->rmxUser['class_ids'];
        }
        // 班级id筛选
        if($this->get("gradeId")) $totalParams['gradeId'] = $data['gradeId'] = $this->get("gradeId");
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        $total = $this->classesModel->get_class_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $data['isDelete'] = 0;
        $classList = $this->classesModel->get_class_list($data);
        foreach($classList as &$class) {
            $class['className'] = $class['class_name'];
        }
        // 返回值
        exit(admin_table_data($total, $classList));   
    }
    // 显示班级荣誉页面
    public function honor_list($classId){
        $this->classId = $classId;
        // 获取相册分类
        $params['classId'] = -1;
        $this->albumCategory = $albumCategory = $this->contentModel->get_album_category($params);
        // 获取相册内容
        foreach($this->albumCategory as &$category) {
            // 获取相册内容
            $albumParams['classId'] = $classId;
            $albumParams['categoryId'] = $category['id'];
            $category['album'] = $this->contentModel->get_album($albumParams);
        }
        // 生成又拍云签名
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceParams = $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);
        
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "honor_list");
    }
    // 删除班级荣誉图片
    public function delete_honor_image(){
        $imageId = $this->post("id");
        $imageInfo = $this->contentModel->get_album_image_info($imageId);
        if(!$imageInfo || $imageInfo['school_id'] != $this->rmxSchool['id']) throw new Exception("删除失败，请刷新后重试");
        // 删除图片
        $this->db->delete(ContentModel::$albumTable, "`id`='{$imageId}'");
        exit(json("删除成功", true));
    }
    // 保存班级荣誉图片
    public function save_honor_action(){
        $imageId = $this->post('id');
        $classId = $this->post("class_id");
        $categoryId = $this->post("category_id");
        $imageLink = $this->post("image_link");
        $imageTitle = $this->post("image_title");
        // 参数检查
        if(!$classId || !$categoryId) throw new Exception("参数错误");
        if(!$imageTitle) throw new Exception("请填写图片标题");
        if(!$imageLink) throw new Exception("请上传图片");
        // 入库
        $data['image_link'] = $imageLink;
        $data['image_desc'] = $imageTitle;
        $data['image_recommend'] = $this->post("image_recommend");
        $data['image_sort'] = $this->post("image_sort");
        $data['updatetime'] = date("Y-m-d H:i:s");
        if($imageId) {
            $this->db->update(ContentModel::$albumTable, $data, "id='{$imageId}'");
        } else {
            $data['school_id'] = $this->rmxSchool['id'];
            $data['campus_id'] = $this->campusInfo['id'];
            $data['class_id'] = $classId;
            $data['category_id'] = $categoryId;
            $data['createtime'] = $data['updatetime'];
            // 多图上传
            $linkArr = explode(',', $imageLink);
            foreach($linkArr as $link) {
                $data['image_link'] = $link;
                $data['image_recommend'] = 0;
                $data['image_sort'] = 0;
                $this->db->insert(ContentModel::$albumTable, $data);
            }
        }
        // 返回值
        $msg = $imageId ? '修改图片成功' : '新增图片成功';
        exit(json($msg, true));
    }

    // 显示考试日程安排表
	public function exam() {
        // 加载数据库类
        $this->load->model('dataModel');
        $this->load->model('schoolModel');
        // 获取学校ID
        $schoolId = $this->rmxSchool['id'];
        $params['schoolId'] = $schoolId;
        // 获取校区ID,同步暂无区分校区
        $params['campusId'] = $this->campusInfo['id'];
        // 根据日期排序
        $orderBy = 'day ASC, begin ASC';
        $params['orderBy'] = $orderBy;
        // 获取年级和科目筛选参数
        $gradeId = $this->get('grade_id');
        $lessonId = $this->get('lesson_id');
        $type = $this->get('type');
        $data['xGradeIdSelect'] = 0;
        $data['xLessonIdSelect'] = 0;
        $data['typeSelect'] = 0;
        if($gradeId){
            $params['gradeId'] = $gradeId;
            $data['xGradeIdSelect'] = $gradeId;
        }
        if($lessonId){
            $params['lessonId'] = $lessonId;
            $data['xLessonIdSelect'] = $lessonId;
        }
        if($type){
            $params['type'] = $type;
            $data['typeSelect'] = $type;
        }
        // 获取哪些属性
        $params['field'] = 'id, day, begin, end, timeslot, part_of_day, lesson_id, grade_id, exam_entry_time_before, exam_entry_time_after, type, exam_id';
        $list = $this->dataModel->get_exam_room_list($params);
        $count = count($list);
        foreach ($list as $key => $val) {
            // 添加星期几属性
            $list[$key]['week'] = date_to_week($val['day']);
            // 通过lesson_id获取科目名
            $lessonInfo = $this->schoolModel->get_lesson_info($val['lesson_id']);
            $list[$key]['lesson_name'] = $lessonInfo['lesson_name'] ? $lessonInfo['lesson_name'] : '';
            // 获取考试年级
            $list[$key]['grade_name'] = '';
            if(!empty($val['grade_id'])){
                $grade = $this->classesModel->get_grade_info($val['grade_id']);
                $list[$key]['grade_name'] = $grade['grade_name'];
                unset($list[$key]['grade_id']);
            }
            // 转换part_of_day为中文
            $list[$key]['part_of_day'] = transform_part_of_day($val['part_of_day']);
            // 计算考试时长
            $duration = get_duration($val['begin'], $val['end']);
            $list[$key]['duration'] = $duration;

            // 转换考试类型为中文
            // 判断是否同时存在等级考和合格考
            $bothHave = false;
            if('chosenExam' === $list[$key]['type']){
                $queryParams['examId'] = $list[$key]['exam_id'];
                $queryParams['lessonId'] = $list[$key]['lesson_id'];
                $queryParams['day'] = $list[$key]['day'];
                $queryParams['timeslot'] = $list[$key]['timeslot'];
                $queryParams['type'] = 'studyExam';
                $queryRes = $this->dataModel->get_exam_room_list($queryParams);
                if(!empty($queryRes)){
                    $bothHave = true;
                }
            }
            if('studyExam' === $list[$key]['type']){
                $queryParams['examId'] = $list[$key]['exam_id'];
                $queryParams['lessonId'] = $list[$key]['lesson_id'];
                $queryParams['day'] = $list[$key]['day'];
                $queryParams['timeslot'] = $list[$key]['timeslot'];
                $queryParams['type'] = 'chosenExam';
                $queryRes = $this->dataModel->get_exam_room_list($queryParams);
                if(!empty($queryRes)){
                    $bothHave = true;
                }
            }
            $list[$key]['type'] = transform_type($list[$key]['type'], $list[$key]['lesson_name'], $bothHave);

            // 添加‘上一场’和‘下一场’的考试id，没有就传0
            $list[$key]['last'] = 0;
            $list[$key]['next'] = 0;
            if ($key > 0) {
                $list[$key]['last'] = $list[$key - 1]['id']; 
            }
            if ($key < ($count - 1)) {
                $list[$key]['next'] = $list[$key + 1]['id'];
            }    
        }
        $ret = array();
        // 数据根据日期分组
        foreach ($list as $val) {  
            $ret[$val['day']][] = $val;
        }
        $data['exams'] = $ret;
        // 获取该校全部年级
        $gradeParams['schoolId'] = $schoolId;
        $gradeParams['isDelete'] = 0;
        $grades = $this->classesModel->get_grade_list($gradeParams);
        // 获取该校全部科目
        $lessonParams['schoolId'] = $schoolId;
        $lessonParams['isDelete'] = 0;
        // 只获取前50条
        $lessonParams['pageStart'] = 0;
        $lessonParams['pageSize'] = 50;

        $lessons = $this->schoolModel->get_lesson_list($lessonParams);
        // 设置全部考试类型
        $types = array(
            'chosenExam' => '选考',
            'studyExam' => '学考',
            'majorExam' => '必考',
            'custom' => '自定义',
            'selfStudy' => '自习',
        );
        $data['grades'] = $grades;
        $data['lessons'] = $lessons;
        $data['types'] = $types;
        // 生成又拍云签名,用于导入
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);
        $this->displayWithData(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "exam", $data);
    }
    
    // 查看考试座位表
	public function exam_room($roomId, $detailId=0) {
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        $this->load->model('dataModel');
        // 为了兼容‘上一场’和‘下一场’
        if($detailId !== 0){
            $ret = $this->dataModel->get_exam_room_detail_info($detailId);
        } else {
            // 获取学校id
            $schoolId = $this->rmxSchool['id'];
            $roomDetailParams['schoolId'] = $schoolId;
            $ret = $this->dataModel->get_exam_room_detail($roomId, $roomDetailParams);
            // 如果是自习类型，就提示‘该场考试为自习类型，没有考场数据’
            if(empty($ret)){
                $this->displayWithData(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "exam_room", $ret);
                return;
            }
            $ret = $ret[0];
        }   
        // 获取考试位置
        if(!empty($ret['location_id'])) {
            $classroom = $this->classesModel->get_classroom_info($ret['location_id'], 1);
            $ret['location'] = isset($classroom['classroom_name']) ? $classroom['classroom_name'] : '';
            // 移除考试位置id
            unset($ret['location_id']);        
        }   
        $students = json_decode($ret['students'], true);
        if (null !== $students) {
            foreach($students as $key => $student){
                $studentInfo = $this->schoolModel->get_student_info($student['userID']);
                // 设置默认值
                $students[$key]['name'] = '';
                $students[$key]['class_name'] = '';
                if(empty($studentInfo) || $studentInfo['is_delete'] == 1){
                    continue;
                }
                // 获取学生姓名
                $students[$key]['name'] = $studentInfo['realname'];
                // 获取学生班级名称
                $class = $this->classesModel->get_class_info($studentInfo['class_id']);
                $students[$key]['class_name'] = $class['class_name'];
                // 获取学生账号xid
                $students[$key]['userID'] = $studentInfo['x_student_id'] ? $studentInfo['x_student_id'] : $studentInfo['id'];
            }
        }
        $ret['students'] = $students;
        // 获取考试时间
        $roomParams['field'] = 'id AS exam_room_id, day, begin, end, lesson_id, type, exam_id, timeslot';
        $roomParams['id'] = $roomId;
        $exam = $this->dataModel->get_exam_room_info($roomParams);
        $exam['week'] = date_to_week($exam['day']);
        $lessonInfo = $this->schoolModel->get_lesson_info($exam['lesson_id']);
        $exam['lesson_name'] = $lessonInfo['lesson_name'];
        $ret = array_merge($ret, $exam);
        // 获取校区ID
        $listParams['campusId'] = $this->campusInfo['id'];
        // 获取学校id
        $schoolId = $this->rmxSchool['id'];
        $listParams['schoolId'] = $schoolId;
        // 根据日期排序
        $orderBy = 'day ASC, begin ASC, x_detail_id ASC';
        $listParams['orderBy'] = $orderBy;
        // 获取哪些属性
        $listParams['field'] = 'ed.id, ed.room_id';
        $list = $this->dataModel->get_exam_room_detail_list($listParams);
        $count = count($list);
        $last = 0;
        $next = 0;
        if($detailId !== 0){
            $ret['id'] = $detailId;
        }
        foreach ($list as $key => $val) {
            if ($val['id'] === $ret['id']) {
                if ($key > 0) {
                    $last = array(
                        'room_id' => $list[$key - 1]['room_id'],
                        'detail_id' => $list[$key - 1]['id']
                    );
                     
                }
                if ($key < ($count - 1)) {
                    $next = array(
                        'room_id' => $list[$key + 1]['room_id'],
                        'detail_id' => $list[$key + 1]['id']
                    );
                } 
            } 
        }
        $ret['last'] = $last;
        $ret['next'] = $next;
        // 转换考试类型为中文
        // 判断是否同时存在等级考和合格考
        $bothHave = false;
        if('chosenExam' === $ret['type']){
            $queryParams['examId'] = $exam['exam_id'];
            $queryParams['lessonId'] = $exam['lesson_id'];
            $queryParams['day'] = $exam['day'];
            $queryParams['timeslot'] = $exam['timeslot'];
            $queryParams['type'] = 'studyExam';
            $queryRes = $this->dataModel->get_exam_room_list($queryParams);
            if(!empty($queryRes)){
                $bothHave = true;
            }
        }
        if('studyExam' === $ret['type']){
            $queryParams['examId'] = $exam['exam_id'];
            $queryParams['lessonId'] = $exam['lesson_id'];
            $queryParams['day'] = $exam['day'];
            $queryParams['timeslot'] = $exam['timeslot'];
            $queryParams['type'] = 'chosenExam';
            $queryRes = $this->dataModel->get_exam_room_list($queryParams);
            if(!empty($queryRes)){
                $bothHave = true;
            }
        }
        $ret['type'] = transform_type($ret['type'], $exam['lesson_name'], $bothHave);
        // 获取监考老师
        $teacherIdArr = explode(',', $ret['inside_teachers']);
        $teacherArr = array();
        foreach($teacherIdArr as $id){
            $teacher = $this->schoolModel->get_teacher_info($id);
            if(!empty($teacher)){
                $teacherArr[] = $teacher['realname'];
            }
        }
        $ret['inside_teachers'] = implode(',', $teacherArr);
        $this->displayWithData(ADMIN_DIR . DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR . "exam_room", $ret);
    }
    
    // 修改考试进场时间
    public function edit_exam_entry_time() {
        $id = $this->post('id');
        $beforeTime = $this->post('before_time');
        $afterTime = $this->post('after_time');
        $data['exam_entry_time_before'] = $beforeTime;
        $data['exam_entry_time_after'] = $afterTime;
        $data['updatetime'] = date("Y-m-d H:i:s");
        $this->db->update(DataModel::$examRoomTable, $data, "id='{$id}'");
        exit(json('修改考试进场时间成功', true));
    }

    // 考试数据管理首页
    public function exam_data() {
        $this->display(ADMIN_DIR . DIRECTORY_SEPARATOR . "contents" . DIRECTORY_SEPARATOR . "exam_data");
    }

    // 获取考试批次列表
    public function get_exam_list() {
        // 获取数据
        $params['pageStart'] = $this->get('start');
        $params['pageSize']= $this->get("length");
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['isDelete'] = 0;
        $examList = $this->dataModel->get_exam_list($params);
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        $totalParams['isDelete'] = 0;
        $total = $this->dataModel->get_exam_list($totalParams);
        // 返回值
        exit(admin_table_data($total, $examList));
    }

    // 考试数据管理页面
    public function exam_room_data($examId) {
        $this->examId = $examId;
        $exam = $this->dataModel->get_exam_info(array(
            'id' => $examId
        ));
        $this->title = $exam['title'];
        $this->display(ADMIN_DIR . DIRECTORY_SEPARATOR . "contents" . DIRECTORY_SEPARATOR . "exam_room_data");
    }

    // 获取考试列表
    public function get_exam_room_list($examId) {
        // 获取数据
        $params['pageStart'] = $this->get('start');
        $params['pageSize']= $this->get("length");
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['isDelete'] = 0;
        if($this->rmxSchool['school_from'] == X_DATA_HAOZHUANYE) {
            // 好专业同步的，使用x_exam_id
            $params['xExamId'] = $examId;
        } else {
            $params['examId'] = $examId;
        }

        // 按时间倒序
        $orderBy = 'day ASC, begin ASC';
        $params['orderBy'] = $orderBy;
        $examRoomList = $this->dataModel->get_exam_room_list($params);
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        $totalParams['isDelete'] = 0;
        if($this->rmxSchool['school_from'] == X_DATA_HAOZHUANYE) {
            // 好专业同步的，使用x_exam_id
            $totalParams['xExamId'] = $examId;
        } else {
            $totalParams['examId'] = $examId;
        }
        $total = $this->dataModel->get_exam_room_list($totalParams);
        // 处理考场相关字段
        foreach($examRoomList as $key => $room){
            // 第一场设为timeslot + 1
            $examRoomList[$key]['timeslot'] = ++ $room['timeslot'];
            // 计算考试时长
            $examRoomList[$key]['duration'] = get_duration($room['begin'], $room['end']);
            // 转换时段没
            $examRoomList[$key]['part_of_day'] = transform_part_of_day($room['part_of_day']);
            // 添加星期几属性
            $examRoomList[$key]['week'] = date_to_week($room['day']);
            // 通过lesson_id获取科目名
            $lessonInfo = $this->schoolModel->get_lesson_info($room['lesson_id']);
            $examRoomList[$key]['lesson_name'] = $lessonInfo['lesson_name'] ? $lessonInfo['lesson_name'] : '';
            // 获取考试年级
            $examRoomList[$key]['grade_name'] = '';
            if(!empty($examRoomList[$key]['grade_id'])){
                $grade = $this->classesModel->get_grade_info($examRoomList[$key]['grade_id']);
                $examRoomList[$key]['grade_name'] = $grade['grade_name'];
                unset($examRoomList[$key]['grade_id']);
            }
            // 转换考试类型为中文
            // 判断是否同时存在等级考和合格考
            $bothHave = false;
            if('chosenExam' === $room['type']){
                $queryParams['examId'] = $room['exam_id'];
                $queryParams['lessonId'] = $room['lesson_id'];
                $queryParams['day'] = $room['day'];
                $queryParams['timeslot'] = $room['timeslot'];
                $queryParams['type'] = 'studyExam';
                $queryRes = $this->dataModel->get_exam_room_list($queryParams);
                if(!empty($queryRes)){
                    $bothHave = true;
                }
            }
            if('studyExam' === $room['type']){
                $queryParams['examId'] = $room['exam_id'];
                $queryParams['lessonId'] = $room['lesson_id'];
                $queryParams['day'] = $room['day'];
                $queryParams['timeslot'] = $room['timeslot'];
                $queryParams['type'] = 'chosenExam';
                $queryRes = $this->dataModel->get_exam_room_list($queryParams);
                if(!empty($queryRes)){
                    $bothHave = true;
                }
            }
            $examRoomList[$key]['type'] = transform_type($room['type'], $examRoomList[$key]['lesson_name'], $bothHave);
        }

// echo '<pre>';var_export($examRoomList);exit;        

        // 返回值
        exit(admin_table_data($total, $examRoomList));
    }

    // 考场数据管理页面
    public function exam_room_detail_data($roomId) {
        // 考试id
        $this->id = $roomId;
        // 获取考试批次id
        $params['id'] = $roomId;
        $roomInfo = $this->dataModel->get_exam_room_info($params);
        $examId = '';
        $title = '';
        if($roomInfo){
            $examId = $roomInfo['exam_id'];
            // 获取考试批次详情
            $examInfo = $this->dataModel->get_exam_info(array('id' => $examId));
            $title = $examInfo['title'];
        }
        $this->examId = $examId;
        $this->title = $title;
        $this->display(ADMIN_DIR . DIRECTORY_SEPARATOR . "contents" . DIRECTORY_SEPARATOR . "exam_room_detail_data");
    }

    // 获取某场考试的考场
    public function get_exam_room_detail_by_roomid() {
        if(empty($this->get('room_id'))){
            throw new Exception('考试id不能为空');
        }
        // 获取数据
        $params['field'] = 'ed.id as detail_id, ed.room_name, ed.inside_teachers, ed.location_id, er.day, er.begin, er.end';
        $params['pageStart'] = $this->get('start');
        $params['pageSize']= $this->get("length");
        $params['roomId'] = $this->get('room_id');
        // 按id倒序
        $params['orderBy'] = 'ed.id DESC';
        $details = $this->dataModel->get_exam_room_detail_list($params); 
        foreach($details as $key => $detail){
            // 获取考试位置
            if(!empty($detail['location_id'])) {
                // 清除上边残存的$this->db->select(field)
                $this->db->reset_query();
                $classroom = $this->classesModel->get_classroom_info($detail['location_id'], 1);
                $details[$key]['location'] = isset($classroom['classroom_name']) ? $classroom['classroom_name'] : '';
                // 移除考试位置id
                unset($details[$key]['location_id']);        
            }
            // 获取监考老师
            $teacherIdArr = explode(',', $detail['inside_teachers']);
            $teacherArr = array();
            foreach($teacherIdArr as $id){
                $teacher = $this->schoolModel->get_teacher_info($id);
                if(!empty($teacher)){
                    $teacherArr[] = $teacher['realname'];
                }
            }
            $details[$key]['inside_teachers'] = implode(',', $teacherArr);
        }

        // 获取数据条数  
        $totalParams['getRowNumber'] = true;
        $totalParams['roomId'] = $this->get('room_id');
        $total = $this->dataModel->get_exam_room_detail_list($totalParams);
        exit(admin_table_data($total, $details));
    }

    // 考场座位数据管理页面
    public function exam_room_detail_student_data($detailId) {
        // 考场id
        $this->detailId = $detailId;
        // 考试id
        $detailInfo = $this->dataModel->get_exam_room_detail_info($detailId);
        $roomId = $detailInfo['room_id'];
        $this->roomId = $roomId;
        // 获取本校区所有的年级
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['isDelete'] = 0;
        $this->grades = $this->classesModel->get_grade_list($params);
        $this->display(ADMIN_DIR . DIRECTORY_SEPARATOR . "contents" . DIRECTORY_SEPARATOR . "exam_room_detail_student_data");
    }

    // 获取考场座位
    public function get_exam_room_detail_student_list() {
        $detailId = $this->get('detail_id');
        $detailInfo = $this->dataModel->get_exam_room_detail_info($detailId);
        $studentJson = $detailInfo['students'];
        $studentArr = array();
        if(!empty(json_decode($studentJson, true))) {
            $studentArr = json_decode($studentJson, true);
        }
        foreach ($studentArr as $key => $student){
            // 获取学生姓名
            $studentArr[$key]['name'] = '';
            $studentArr[$key]['class_name'] = '';
            // 当学生没有xid，就把教育id设置为学生id
            $studentArr[$key]['xid'] = $student['userID'];
            $studentInfo = $this->schoolModel->get_student_info($student['userID']);
            if(!empty($studentInfo)){
                // 获取学生姓名
                $studentArr[$key]['name'] = $studentInfo['realname'];
                // 获取学生班级名称
                $class = $this->classesModel->get_class_info($studentInfo['class_id']);
                $studentArr[$key]['class_name'] = $class['class_name'];
                // 获取学生账号xid
                $studentArr[$key]['xid'] = $studentInfo['x_student_id'];
            }
            // 把userID属性放到最后，便于按座位号排序
            $userID = $student['userID'];
            unset($studentArr[$key]['userID']);
            $studentArr[$key]['userID'] = $userID;
        }
        
        // 按座位号排序
        sort($studentArr);
        exit(admin_table_data(count($studentArr), $studentArr));
    }

    // 选择资源年级插件数据源
    public function select_student_plugin_data_source() {
        // // 获取哪一个学校的
        // $schoolId = $this->get('school_id');
        // if($schoolId){
        //     $params['schoolId'] = $schoolId;
        // }
        // // 获取哪个校区的
        // $campusId = $this->get('campus_id');
        // if($campusId){
        //     $params['campusId'] = $campusId;
        // }
        // 获取某一个年级的
        $gradeId = $this->get('grade_id');
        if(empty($gradeId)){
            throw new Exception('grade_id不能为空');
        }
        $classList = $this->classesModel->get_class_list_by_grade($gradeId);
        // 资源年级预定义
        $studentArr = array();
        foreach($classList as $class) {
            $classId = $class['id'];
            // 初始化数据
            $className = $class['class_name'];
            $tree['text'] = $className;
            $tree['type'] = 'folder';
            $tree['attr'] = array("id" => $classId);

            $class['additionalParameters']['children'] = array();
            $studentArr["label_". $classId] = $tree;

            $params['isDelete'] = 0;
            $params['classId'] = $classId;
            $students = $this->schoolModel->get_student_list($params);
            foreach($students as $student) {
                $stdTree['text'] = $student['realname'];
                $stdTree['type'] = 'item';
                $stdTree['attr'] = array('id' => $student['id']);

                $studentArr["label_". $classId]['additionalParameters']['children'][] = $stdTree;
            }
        }
        exit(json('', true, $studentArr));
    }

    // 保存考试学生座位
    public function save_exam_student_action() {
        $detailId = $this->post('detail_id');
        $ids = $this->post('id');
        $ticket = trim($this->post('ticket'));
        if(empty($ticket)){
            throw new Exception('准考证号不能为空');
        }
        if(empty($detailId)) {
            throw new Exception('考场id不能为空');
        }
        $idArr = explode(',', $ids);
        $detailInfo = $this->dataModel->get_exam_room_detail_info($detailId);
        $studentJson = $detailInfo['students'];
        $studentArr = array();
        if(!empty(json_decode($studentJson, true))) {
            $studentArr = json_decode($studentJson, true);
        }
        foreach ($studentArr as $key => $student){
            // 把userID属性放到最后，便于按座位号排序
            $userID = $student['userID'];
            unset($studentArr[$key]['userID']);
            $studentArr[$key]['userID'] = $userID;
        }
        // 按座位号排序
        sort($studentArr);
        // 获取最大座位号
        $maxSeatNO = 0;
        if(count($studentArr) > 0) {
            $maxSeatNO = $studentArr[count($studentArr) - 1]['seatNO'];
        }
        foreach($idArr as $id){
            // 判断学生是不是已在改考场中
            foreach($studentArr as $stu){
                if($stu['userID'] == $id){
                    $studentExist = $this->schoolModel->get_student_info($id);
                    $username = $studentExist ? $studentExist['realname'] : $id;
                    throw new Exception('学生：' . $username . '已在该考场中!');
                }
            }
            // 座位号
            $seatNO = (int) $maxSeatNO + 1;
            array_push($studentArr, array(
                'userID' => $id,
                'seatNO' => $seatNO,
                'studentTicket' => $ticket
            ));
            if(is_numeric($ticket)){ 
                // 准考证号纯数字
                $ticket =  (int) $ticket; 
                $ticket = $ticket + 1;
            } else {
                // 非纯数字，后面的3位数字加一，再进行拼接
                // 准考证号大于3位
                if(mb_strlen($ticket) > 3){
                    // 后面3位
                    $end = substr($ticket, -3);
                    // 前面剩余部分
                    $start = substr($ticket, 0, -3);
                    $end = (int) $end + 1;
                    $ticket = $start . $end; 
                }
            }
        }
        // 索引值如何重新从0开始递增
        $studentArr = array_values($studentArr);
        // 座位重新从1开始
        foreach($studentArr as $key => $student) {
            $studentArr[$key]['seatNO'] = $key + 1;
        }
        $this->db->where('id', $detailId);
        $this->db->update(DataModel::$examRoomDetailTable, array(
            'students' => json_encode($studentArr, JSON_UNESCAPED_UNICODE)
        ));
        exit(json('保存成功', true));
    }

    // 修改考场学生
    public function edit_exam_student_action(){
        $detailId = $this->post('detail_id');
        $userID = $this->post('id');
        $seatNO = $this->post('seat_no');
        $ticket = $this->post('ticket');
        if(empty($detailId)){
            throw new Exception('detailId不能为空');
        }
        if(empty($userID)){
            throw new Exception('userId不能为空');
        }
        if(empty($seatNO)){
            throw new Exception('座位号不能为空');
        }
        if(empty($ticket)){
            throw new Exception('准考证号不能为空');
        } 
        $detailInfo = $this->dataModel->get_exam_room_detail_info($detailId);
        $studentJson = $detailInfo['students'];
        $studentArr = json_decode($studentJson, true);
        foreach ($studentArr as $key => $student){
            // 修改该考生
            if($student['userID'] == $userID) {
                $studentArr[$key] = array(
                    'seatNO' => $seatNO,
                    'studentTicket' => $ticket,
                    'userID' => $userID
                );
                break;
            }
        }
        $this->db->where('id', $detailId);
        $this->db->update(DataModel::$examRoomDetailTable, array(
            'students' => json_encode($studentArr, JSON_UNESCAPED_UNICODE)
        ));
        exit(json('修改成功', true));
    }

    // 删除考场学生
    public function delete_exam_student_action(){
        $detailId = $this->post('detail_id');
        $id = $this->post('id');
        if(empty($detailId)){
            throw new Exception('detailId不能为空');
        }
        if(empty($id)){
            throw new Exception('userId不能为空');
        }
        $detailInfo = $this->dataModel->get_exam_room_detail_info($detailId);
        $studentJson = $detailInfo['students'];
        $studentArr = json_decode($studentJson, true);  
        foreach ($studentArr as $key => $student){
            // 删除该考生
            if($student['userID'] == $id) {
                unset($studentArr[$key]);
                continue;
            }
            // 把userID属性放到最后，便于按座位号排序
            $userID = $student['userID'];
            unset($studentArr[$key]['userID']);
            $studentArr[$key]['userID'] = $userID;
        }
        // 按座位号排序
        sort($studentArr);
        // 索引值如何重新从0开始递增
        $studentArr = array_values($studentArr);
        // 座位重新从1开始
        foreach($studentArr as $key => $student) {
            $studentArr[$key]['seatNO'] = $key + 1;
        }
        $this->db->where('id', $detailId);
        $this->db->update(DataModel::$examRoomDetailTable, array(
            'students' => json_encode($studentArr, JSON_UNESCAPED_UNICODE)
        ));
        exit(json('删除成功', true));
    }

    // 保存考试批次
    public function save_exam_action(){
        $id = $this->post('id');
        $title = trim($this->post('title'));
        if(empty($title)){
            throw new Exception('标题不能为空');
        }
        if(empty($id)){
            // 新增操作
            $this->db->insert(DataModel::$examTable, array(
                'school_id' => $this->rmxSchool['id'],
                'campus_id' => $this->campusInfo['id'],
                'is_delete' => 0,
                'title' => $title,
                'createtime' => date('Y-m-d H:i:s'),
                'updatetime' => date('Y-m-d H:i:s')
            ));
            $msg = '添加成功';
        } else {
            // 更新操作
            $this->db->where('id', $id);
            $this->db->update(DataModel::$examTable, array(
                'title' => $title,
                'updatetime' => date('Y-m-d H:i:s')
            ));
            $msg = '修改成功';
        }
        exit(json($msg, true));
    }

    // 删除考试批次
    public function delete_exam_action(){
        $id = $this->post('id');
        if(empty($id)){
            throw new Exception('批次id不能为空');
        }
        // 获取该批次的所有考试
        $roomParams['schoolId'] = $this->rmxSchool['id'];
        $roomParams['campusId'] = $this->campusInfo['id'];
        $roomParams['examId'] = $id;
        $examRooms = $this->dataModel->get_exam_room_list($roomParams);
        // 获取该批次的所有考场
        $detailParams['schoolId'] = $this->rmxSchool['id'];
        $detailParams['campusId'] = $this->campusInfo['id'];
        $detailsAll = array();
        foreach ($examRooms as $room) {
            $details = $this->dataModel->get_exam_room_detail_list_by_roomId($room['id']);
            $detailsAll = array_merge($detailsAll, $details);
        }
        // 删除批次
        $arr = array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->where('id', $id);
        $this->db->update(DataModel::$examTable, $arr);
        // 删除考试
        foreach($examRooms as $room){
            $this->db->where('id', $room['id']);
            $this->db->update(DataModel::$examRoomTable, $arr);
        }
        // 删除考场
        foreach($detailsAll as $detail){
            $this->db->where('id', $detail['id']);
            $this->db->update(DataModel::$examRoomDetailTable, $arr);
        }
        exit(json('删除成功', true));
    }

    // 编辑考试表单页面
    public function save_exam_room_page() {
        $examId = $this->get('exam_id');
        if(empty($examId)){
            throw new Exception('exam_id不能为空');
        }
        $roomId = $this->get('room_id');
        if(!empty($roomId)){
            $this->roomId = $roomId;
            $room = $this->dataModel->get_exam_room_info(array(
                'id' => $roomId
            ));
            // 场次timeslot+1
            $room['timeslot'] ++;
            // 获取巡考教师名称
            $teacherNameArr = array();
            $teacherIdArr = explode(',', $room['outside_teachers']);
            foreach ($teacherIdArr as $teacherId) {
                $teacher = $this->schoolModel->get_school_user_info_realname($teacherId);
                if($teacher) {
                    $teacherName = $teacher['realname'] ? $teacher['realname'] : $teacher['username'];
                    array_push($teacherNameArr, $teacherName);
                }
            }
            // 获取放学学生名称
            $studentNameArr = array();
            $studentIdArr = explode(',', $room['free_students']);
            foreach ($studentIdArr as $studentId) {
                $student = $this->schoolModel->get_student_info($studentId);
                if($student) {
                    $studentName = $student['realname'];
                    array_push($studentNameArr, $studentName);
                }
            }
            $room['teacherNames'] = implode('，', $teacherNameArr);
            $room['studentNames'] = implode('，', $studentNameArr); 
            $this->room = $room;
        }
        $this->examId = $examId;
        // 获取本校所有年级
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['isDelete'] = 0;
        $this->grades = $this->classesModel->get_grade_list($params);
        // 过滤掉‘功能课室’
        foreach($this->grades as $key => &$grade) {
            if($grade['school_id'] == 0) {
                unset($this->grades[$key]);
            }
        }
        // 获取本校所有科目
        $this->subjects = $this->schoolModel->get_lesson_list($params);
        // 获取所有考试类型
        $this->types = array(
            EXAM_TYPE_CHOSEN => transform_exam_type_to_chinese(EXAM_TYPE_CHOSEN),
            EXAM_TYPE_MAJOR => transform_exam_type_to_chinese(EXAM_TYPE_MAJOR),
            EXAM_TYPE_CUSTOM => transform_exam_type_to_chinese(EXAM_TYPE_CUSTOM),
            EXAM_TYPE_STUDY => transform_exam_type_to_chinese(EXAM_TYPE_STUDY),
            EXAM_TYPE_SELF => transform_exam_type_to_chinese(EXAM_TYPE_SELF)
        );
        $this->display(ADMIN_DIR . DIRECTORY_SEPARATOR . "contents" . DIRECTORY_SEPARATOR . "save_exam_room_page");
    }

    // 保存考试
    public function save_exam_room_action() {
        $examId = $this->post('exam_id');
        $roomId = $this->post('room_id');
        $timeslot = trim($this->post('timeslot'));
        $outsideTeacherIds = $this->post('outside_teacher_ids');
        $freeStudentIds = $this->post('free_student_ids');
        $gradeId = $this->post('grade');
        $subjectId = $this->post('subject');
        $day = $this->post('day');
        $begin = $this->post('start');
        $end = $this->post('end');
        $type = $this->post('type');
        if(empty($examId)) {
            throw new Exception('exam_id不能为空');
        } 
        if(empty($timeslot)) {
            throw new Exception('场次不能为空');
        }
        if((int) $timeslot < 1){
            throw new Exception('场次不能小于1');
        }
        if(empty($gradeId)) {
            throw new Exception('年级不能为空');
        }
        if(empty($subjectId)) {
            throw new Exception('科目不能为空');
        }
        if(empty($day)) {
            throw new Exception('日期不能为空');
        }
        if(empty($begin)) {
            throw new Exception('时间不能为空');
        }
        if(empty($end)) {
            throw new Exception('时间不能为空');
        }
        if(empty($type)) {
            throw new Exception('类型不能为空');
        }
        if($begin >= $end) {
            throw new Exception('开始时间必须小于结束时间');
        }
        if(empty($roomId)) {
            // 添加操作
            $this->db->insert(DataModel::$examRoomTable, array(
                'school_id' => $this->rmxSchool['id'],
                'campus_id' => $this->campusInfo['id'],
                'exam_id' => $examId,
                'timeslot' => $timeslot - 1,
                'outside_teachers' => $outsideTeacherIds,
                'free_students' => $freeStudentIds,
                'grade_id' => $gradeId,
                'lesson_id' => $subjectId,
                'day' => $day,
                'begin' => $begin,
                'end' => $end,
                'type' => $type,
                'part_of_day' => get_part_of_day($begin),
                'is_delete' => 0,
                'createtime' => date('Y-m-d H:i:s'),
                'updatetime' => date('Y-m-d H:i:s')
            ));
            $msg = '添加成功';
        } else {
            // 修改操作
            $this->db->where('id', $roomId);
            $this->db->update(DataModel::$examRoomTable, array(
                'timeslot' => $timeslot - 1,
                'outside_teachers' => $outsideTeacherIds,
                'free_students' => $freeStudentIds,
                'grade_id' => $gradeId,
                'lesson_id' => $subjectId,
                'day' => $day,
                'begin' => $begin,
                'end' => $end,
                'type' => $type,
                'part_of_day' => get_part_of_day($begin),
                'updatetime' => date('Y-m-d H:i:s')
            ));
            $msg = '修改成功';
        }
        exit(json($msg, true));
    }

    // 删除考试
    public function delete_exam_room_action(){
        $roomId = $this->post('room_id');
        if(empty($roomId)){
            throw new Exception('考试id不能为空');
        }
        // 获取该考试的所有考场
        $details = $this->dataModel->get_exam_room_detail_list_by_roomId($roomId);
        // 删除考试
        $arr = array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->where('id', $roomId);
        $this->db->update(DataModel::$examRoomTable, $arr);
        // 删除考场
        foreach($details as $detail){
            $this->db->where('id', $detail['id']);
            $this->db->update(DataModel::$examRoomDetailTable, $arr);
        }
        exit(json('删除成功', true));
    }

    // 编辑考场表单页面
    public function save_exam_room_detail_page() {
        $roomId = $this->get('room_id');
        if(empty($roomId)){
            throw new Exception('考试id不能为空');
        }
        $detailId = $this->get('detail_id');
        if(!empty($detailId)){
            $this->detailId = $detailId;
            $detail = $this->dataModel->get_exam_room_detail_info($detailId);
            // 获取监考教师名称
            $teacherNameArr = array();
            $teacherIdArr = explode(',', $detail['inside_teachers']);
            foreach ($teacherIdArr as $teacherId) {
                $teacher = $this->schoolModel->get_school_user_info_realname($teacherId);
                if($teacher) {
                    $teacherName = $teacher['realname'] ? $teacher['realname'] : $teacher['username'];
                    array_push($teacherNameArr, $teacherName);
                }
            }
            $detail['teacherNames'] = implode('，', $teacherNameArr);
            $this->detail = $detail;
        }
        $this->roomId = $roomId;
        // 获取本校区所有课室
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['isDelete'] = 0;
        $this->classrooms = $this->classesModel->get_classroom_list($params);

        $this->display(ADMIN_DIR . DIRECTORY_SEPARATOR . "contents" . DIRECTORY_SEPARATOR . "save_exam_room_detail_page");
    }

    // 保存考场
    public function save_exam_room_detail_action() {
        $roomId = $this->post('room_id');
        $detailId = $this->post('detail_id');
        $roomName = trim($this->post('room_name'));
        $insideTeacherIds = $this->post('inside_teacher_ids');
        $locationId = $this->post('location_id');
        $roomNo = trim($this->post('room_no'));
        if(empty($roomId)) {
            throw new Exception('考试id不能为空');
        }
        if(empty($roomName)) {
            throw new Exception('考场名称不能为空');
        } 
        if(empty($roomNo)) {
            throw new Exception('编号不能为空');
        }
        if(empty($detailId)) {
            // 添加操作
            $this->db->insert(DataModel::$examRoomDetailTable, array(
                'school_id' => $this->rmxSchool['id'],
                'campus_id' => $this->campusInfo['id'],
                'room_id' => $roomId,
                'room_name' => $roomName,
                'inside_teachers' => $insideTeacherIds,
                'location_id' => $locationId,
                'room_no' => $roomNo,
                'is_delete' => 0,
                'createtime' => date('Y-m-d H:i:s'),
                'updatetime' => date('Y-m-d H:i:s')
            ));
            $msg = '添加成功';
        } else {
            // 修改操作
            $this->db->where('id', $detailId);
            $this->db->update(DataModel::$examRoomDetailTable, array(
                'room_name' => $roomName,
                'inside_teachers' => $insideTeacherIds,
                'location_id' => $locationId,
                'room_no' => $roomNo,
                'updatetime' => date('Y-m-d H:i:s')
            ));
            $msg = '修改成功';
        }
        exit(json($msg, true));
    }

    // 删除考场
    public function delete_exam_room_detail_action() {
        $id = $this->post('id');
        $this->db->where('id', $id);
        $this->db->update(DataModel::$examRoomDetailTable, array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        ));

        exit(json('删除成功', true));
    }

    // 学生成绩大项页面
	public function result_major() {
        // 加载数据库类
        $this->load->model('dataModel');
        $this->load->model('schoolModel');
        // 获取学校ID
        $schoolId = $this->rmxSchool['id'];
        $params['schoolId'] = $schoolId;

        // 生成又拍云签名,用于导入
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "result_major");
    }

    // 学生成绩数据管理页面
	public function result_major_data() {
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "result_major_data");
    }
    // 获取成绩大项列表
    public function get_result_major_list() {
        // 获取数据
        $params['pageStart'] = $this->get('start');
        $params['pageSize']= $this->get("length");
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['isDelete'] = 0;
        $resultMajorList = $this->dataModel->get_result_major_list($params);
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        $totalParams['isDelete'] = 0;
        $total = $this->dataModel->get_result_major_list($totalParams);
        foreach($resultMajorList as &$major) {
            $major['is_show_chinese'] = $major['is_show'] ? '是' : '否';
        }
        // 返回值
        exit(admin_table_data($total, $resultMajorList));
    }
    // 保存成绩大项操作
    public function save_result_major_action() {
        $id = $this->post('id');
        $title = trim($this->post('title'));
        $sort = $this->post('sort');
        $isShow = $this->post('is_show');
        if(empty($title)){
            throw new Exception('标题不能为空');
        }
        if(empty($id)){
            // 新增操作
            $this->db->insert(DataModel::$resultMajorTable, array(
                'school_id' => $this->rmxSchool['id'],
                'campus_id' => $this->campusInfo['id'],
                'is_delete' => 0,
                'title' => $title,
                'sort' => $sort,
                'is_show' => $isShow,
                'createtime' => date('Y-m-d H:i:s'),
                'updatetime' => date('Y-m-d H:i:s')
            ));
            $msg = '添加成功';
        } else {
            // 更新操作
            $this->db->where('id', $id);
            $this->db->update(DataModel::$resultMajorTable, array(
                'title' => $title,
                'sort' => $sort,
                'is_show' => $isShow,
                'updatetime' => date('Y-m-d H:i:s')
            ));
            $msg = '修改成功';
        }
        exit(json($msg, true));
    }
    // 删除成绩大项
    public function delete_result_major_action(){
        $id = $this->post('id');
        if(empty($id)){
            throw new Exception('id不能为空');
        }
        // 删除成绩大项
        $arr = array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(DataModel::$resultMajorTable, $arr, array('id' => $id));
        // 获取对应的年级项列表
        $params['isDelete'] = 0;
        $params['majorId'] = $id;
        $resultGradeList = $this->dataModel->get_result_grade_list($params);
        if($resultGradeList) {
            foreach($resultGradeList as $resultGrade) {
                // 删除成绩
                $this->db->update(DataModel::$resultTable, $arr, array("result_grade_id" => $resultGrade['id']));
            }   
            // 删除年级项
            $this->db->update(DataModel::$resultGradeTable, $arr, array("major_id" => $id));
        }
        exit(json('删除成功', true));
    }
    // 成绩年级项页面
	public function result_grade_data($majorId) {
        $this->majorId = $majorId;
        $major = $this->dataModel->get_result_major_info($majorId);
        $this->title = $major['title'];
        // 生成又拍云签名,用于导入
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "result_grade_data");
    }
    // 导出年级成绩模板
    public function export_grade_result($resultGradeId) {
        $resultGrade = $this->dataModel->get_result_grade_info($resultGradeId);
        // 获取学校所有科目
        $lesParams['schoolId'] = $this->rmxSchool['id'];
        $lesParams['isDelete'] = 0;
        $subjectArr = $this->schoolModel->get_lesson_list($lesParams);
        // 用id作为键值
        $subjectArr = array_value_to_key($subjectArr, 'id');
        // 获取考试科目id数组
        $resultGrade['subjectIdArr'] = explode(',', $resultGrade['subject_ids']);
        // 获取科目名称
        $subjectNameArr = array();
        foreach($resultGrade['subjectIdArr'] as $subjectId) {
            if(isset($subjectArr[$subjectId])) {
                array_push($subjectNameArr, $subjectArr[$subjectId]['lesson_name']);
            }
        }
        $resultGrade['subjectNameArr'] = $subjectNameArr;
        // echo'<pre>';var_export($resultGrade);exit;
        // 获取年级所有学生
        $classList = $this->classesModel->get_class_list_by_grade($resultGrade['grade_id']);
        $studentArr = array();
        foreach($classList as $class) {
            $classId = $class['id'];
            // 初始化数据
            $className = $class['class_name'];
            $params['isDelete'] = 0;
            $params['classId'] = $classId;
            // 按座位号排序
            $params['orderBy'] = 'seat_no ASC';
            $students = $this->schoolModel->get_student_list($params);

            if($students) {
                // foreach($students as $key => $student) {
                //     // 获取首字母
                //     $students[$key]['realnameFirstChar'] = getFirstChar($student['realname']);
                // }
                // 按姓名首字母排序
                // $timeKey =  array_column($students, 'realnameFirstChar');
                // array_multisort($timeKey, SORT_ASC, $students);
                foreach($students as $student) {
                    $studentArr[$className][] = array(
                        'id' => $student['id'],
                        'realname' => $student['realname'],
                        'seat_no' => $student['seat_no']
                    );
                }
            }
        }
        if(empty($studentArr)) {
            echo "<script>alert('该年级无学生数据');</script>";
            exit;
        }
        // 学生列表按班级名称，座位号排序
        // $studentArr = 
        $firstRow = array(
            '学生名称',
            '年级名称',
            '班级名称',
            '座位号'
        );
        foreach($subjectNameArr as $subjectName) {
            $firstRow[] = $subjectName;
        }
        $data = array ();
        $data[] = $firstRow;
        $gradeInfo = $this->classesModel->get_grade_info($resultGrade['grade_id']);
        // 获取年级学生成绩
        $resultParams['resultGradeId'] = $resultGradeId;
        $resultList = $this->dataModel->get_result_list($resultParams);
        // 使用学生id作为键值
        $resultList = array_value_to_key($resultList, 'student_id');

        foreach($studentArr as $className =>  $studentArr) {
            foreach($studentArr as $student) {
                $row = array(
                    $student['realname'],
                    $gradeInfo['grade_name'],
                    $className,
                    $student['seat_no']
                );
                // 获取学生成绩
                foreach($resultGrade['subjectIdArr'] as $subjectId) {
                    if(isset($resultList[$student['id']])) {
                        $valueArr = json_decode($resultList[$student['id']]['value'], true);
                        // var_export($valueArr);exit;
                        // 使用subjectId作为键值
                        $valueArr = array_value_to_key($valueArr, 'subject_id');
                        if(isset($valueArr[$subjectId])) {
                            $row[] = $valueArr[$subjectId]['score'];
                        } else {
                            $row[] = 0;
                        }
                    } else {
                        $row[] = 0;
                    }
                }
                $data[] = $row;
            }
        }
        $resultMajor = $this->dataModel->get_result_major_info($resultGrade['major_id']);
        $filename = $resultMajor['title'] . $gradeInfo['grade_name'] . '成绩模板';
        if(strlen($filename) > 50) {
            $filename = $gradeInfo['grade_name'] . '成绩模板';
        }
        // var_export(strlen($filename));exit;
        // 导出excel
        $widthParams = array(
            array(
                'index' => 'C',
                'width' => 16
            )
        );
        // echo'<pre>';var_export($data);exit;
        exportExcel($filename, $data, $widthParams);
    }
    // 发送成绩通知
    public function notify_grade_result($id) {
        $resultGrade = $this->dataModel->get_result_grade_info($id);
        $major = $this->dataModel->get_result_major_info($resultGrade['major_id']);
        $majorTitle = $major['title'];
        // 获取年级下的班级列表
        $classList = $this->classesModel->get_class_list_by_grade($resultGrade['grade_id']);
        if(empty($classList)) {
            throw new Exception('该年级无学生数据');
        }
        $classIdArr = array();
        foreach($classList as $class) {
            array_push($classIdArr, $class['id']);
        }
        $classIds = implode(',', $classIdArr);
        // 获取学生列表
        $stuParams['isDelete'] = 0;
        $stuParams['schoolId'] = $this->rmxSchool['id'];
        $stuParams['campusId'] = $this->campusInfo['id'];
        $stuParams['classSet'] = $classIds;
        $studentList = $this->schoolModel->get_student_list($stuParams);
        if(empty($studentList)) {
            throw new Exception('该年级无学生数据');
        }
        // 获取成绩列表
        $resultParams['resultGradeId'] = $id;
        $resultParams['isDelete'] = 0;
        $resultList = $this->dataModel->get_result_list($resultParams);
        // 使用学生id作为键值
        $resultList = array_value_to_key($resultList, 'student_id');
        if(empty($resultList)) {
            throw new Exception('该年级暂无成绩数据');
        }

        $this->load->library('wxtemplate');
        $url = wx_url('classes/my_result_detail/' . $major['id']);
        $processDataArr = array();
        foreach($studentList as $student) {
            if(isset($resultList[$student['id']])) {
                $resultValue = $resultList[$student['id']]['value'];
                $valueArr = json_decode($resultValue, true);
                $score = '';
                foreach($valueArr as $value) {
                    $score .= $value['subject_name'] . $value['score'] . '分；';
                }
                // 发送模板消息
                $data = array(
                    // 'first' => array(
                    //     'value' => '亲爱的家长，' . $student['realname'] . '同学本次考试成绩如下：'
                    // ),
                    'keyword1' => array(
                        'value' => $student['realname']
                    ),
                    'keyword2' => array(
                        'value' => $majorTitle
                    ),
                    'keyword3' => array(
                        'value' => $score
                    )
                );
                array_push($processDataArr, array(
                    'student_id' => $student['id'],
                    'data' => $data 
                ));
                // $this->wxtemplate->send_template_msg_for_user($student['id'], BIND_TYPE_STUDENT, WX_TEMPLATE_RESULT_NOTIFY, $data, $url);
            }
        }
        // 后台进程
        if($processDataArr) {
            $this->load->model('wxUserModel');
            // 截取成100个
            $arr = array_chunk($processDataArr, 100);
            foreach($arr as $processData) {
                $this->db->insert(WxUserModel::$wxTemplateProcessTable, array(
                    'template_id' => WX_TEMPLATE_RESULT_NOTIFY,
                    'type' => 'student',
                    'data' => json_encode($processData, JSON_UNESCAPED_UNICODE),
                    'url' => $url
                ));
            }

        }

        exit(json('发送通知完成', true));
    }
    // 获取年级项列表
    public function get_result_grade_list($majorId) {
        // 获取数据
        $params['pageStart'] = $this->get('start');
        $params['pageSize']= $this->get("length");
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['majorId'] = $majorId;
        $params['isDelete'] = 0;
        $resultGradeList = $this->dataModel->get_result_grade_list($params);
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        $totalParams['majorId'] = $majorId;
        $totalParams['isDelete'] = 0;
        $total = $this->dataModel->get_result_grade_list($totalParams);
        // 获取学校所有科目
        $lesParams['schoolId'] = $this->rmxSchool['id'];
        $lesParams['isDelete'] = 0;
        $subjectArr = $this->schoolModel->get_lesson_list($lesParams);
        // 用id作为键值
        $subjectArr = array_value_to_key($subjectArr, 'id');
        foreach($resultGradeList as &$resultGrade) {
            $resultGrade['show_grade_rank_chinese'] = $resultGrade['show_grade_rank'] ? '是' : '否';
            $resultGrade['show_class_rank_chinese'] = $resultGrade['show_class_rank'] ? '是' : '否';
            // 获取年级名称
            $gradeInfo = $this->classesModel->get_grade_info($resultGrade['grade_id']);
            if($gradeInfo) {
                $resultGrade['grade_name'] = $gradeInfo['grade_name'];
            } else {
                $resultGrade['grade_name'] = '';
            }
            // 获取考试科目
            if(empty($resultGrade['subject_ids'])) {
                $subjectIdArr = array();
            } else {
                $subjectIdArr = explode(',', $resultGrade['subject_ids']);
            }
            $subjectNameArr = array();
            foreach($subjectIdArr as $subjectId) {
                $subject = $subjectArr[$subjectId];
                array_push($subjectNameArr, $subject['lesson_name']);
            }
            $resultGrade['subject_names'] = implode(',', $subjectNameArr);
        }
        // 返回值
        exit(admin_table_data($total, $resultGradeList));
    }
    // 编辑年级项页面
    public function edit_result_grade_page() {
        $majorId = $this->get('major_id');
        if(empty($majorId)){
            throw new Exception('major_id不能为空');
        }
        $resultGradeId = $this->get('result_grade_id');
        if(!empty($resultGradeId)){
            $this->resultGradeId = $resultGradeId;
            $resultGrade = $this->dataModel->get_result_grade_info($resultGradeId);
            // 获取考试科目id数组
            $resultGrade['subjectIdArr'] = explode(',', $resultGrade['subject_ids']);
            $this->resultGrade = $resultGrade;
        }
        $this->majorId = $majorId;
        // 获取本校所有年级
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['isDelete'] = 0;
        $this->grades = $this->classesModel->get_grade_list($params);
        // 过滤掉‘功能课室’
        foreach($this->grades as $key => &$grade) {
            if($grade['school_id'] == 0) {
                unset($this->grades[$key]);
            }
        }
        // 获取学校所有科目
        $lesParams['schoolId'] = $this->rmxSchool['id'];
        $lesParams['isDelete'] = 0;
        $this->subjectArr = $this->schoolModel->get_lesson_list($lesParams);
        $this->display(ADMIN_DIR . DIRECTORY_SEPARATOR . "contents" . DIRECTORY_SEPARATOR . "edit_result_grade_page");
    }
    // 保存年级项
    public function save_result_grade_action() {
        $majorId = $this->post('major_id');
        $resultGradeId = $this->post('result_grade_id');
        $showGradeRank = $this->post('show_grade_rank');
        $showClassRank = $this->post('show_class_rank');
        $subject = $this->post('subject');

        if(empty($subject)) {
            throw new Exception('考试科目不能为空');
        }
        if(empty($resultGradeId)) {
            $gradeId = $this->post('grade');
            // 判断该年级是否已添加过
            $resultGradeInfo = $this->dataModel->get_result_grade_info_by_grade_id($majorId, $gradeId);
            if($resultGradeInfo) {
                throw new Exception('该年级项已存在');
            }
            // 添加操作
            $this->db->insert(DataModel::$resultGradeTable, array(
                'school_id' => $this->rmxSchool['id'],
                'campus_id' => $this->campusInfo['id'],
                'major_id' => $majorId,
                'grade_id' => $gradeId,
                'show_grade_rank' => $showGradeRank,
                'show_class_rank' => $showClassRank,
                'subject_ids' => $subject,
                'is_delete' => 0,
                'createtime' => date('Y-m-d H:i:s'),
                'updatetime' => date('Y-m-d H:i:s')
            ));
            $msg = '添加成功';
        } else {
            // 获取删除的科目    
            $resultGradeInfo = $this->dataModel->get_result_grade_info($resultGradeId);
            if($subject != $resultGradeInfo['subject_ids']) {
                $newIdArr = explode(',', $subject);
                $idArr = explode(',', $resultGradeInfo['subject_ids']);
                $removeIdArr = array();
                foreach($idArr as $id) {
                    if(!in_array($id, $newIdArr)) {
                        array_push($removeIdArr, $id);
                    }
                }

                if($removeIdArr) {
                    // 判断删除的科目是否已录入成绩
                    foreach($removeIdArr as $id) {
                        $subjectInfo = $this->schoolModel->get_lesson_info($id);
                        $value = '"subject_id":"' . $id . '"';
                        $notLikeValue = '"subject_id":"' . $id . '","subject_name":"' . $subjectInfo['lesson_name'] . '","score":0}';
                        $info = $this->dataModel->get_result_info_by_value($resultGradeId, $value, $notLikeValue);
                        if($info) {
                            throw new Exception('科目：' . $subjectInfo['lesson_name'] . '已存在成绩数据，请先清空该科成绩');
                        }
                    }
                }
            }

            // 修改操作;
            $this->db->update(DataModel::$resultGradeTable, array(
                'show_grade_rank' => $showGradeRank,
                'show_class_rank' => $showClassRank,
                'subject_ids' => $subject,
                'updatetime' => date('Y-m-d H:i:s')
            ), "id = {$resultGradeId}");
            $msg = '修改成功';
        }
        exit(json($msg, true));
    }
    // 删除成绩年级项
    public function delete_result_grade_action(){
        $id = $this->post('result_grade_id');
        if(empty($id)){
            throw new Exception('id不能为空');
        }
        // 删除成绩大项
        $arr = array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        );;
        $this->db->update(DataModel::$resultGradeTable, $arr, array("id" => $id));
        // 同时删除年级项的成绩
        $this->db->update(DataModel::$resultTable, $arr, array("result_grade_id" => $id));
        exit(json('删除成功', true));
    }
    // 学生成绩页面
	public function result_data($resultGradeId) {
        $this->resultGradeId = $resultGradeId;
        // 获取年级项信息
        $resultGrade = $this->dataModel->get_result_grade_info($resultGradeId);
        $subjectIdArr = explode(',', $resultGrade['subject_ids']);
        // 获取学校科目列表
        $subjectList = $this->schoolModel->get_lesson_list(array(
            'schoolId' => $this->rmxSchool['id'],
            'isDelete' => 0
        ));
        // 用id作为键值
        $subjectList = array_value_to_key($subjectList, 'id');
        // echo '<pre>';var_export($subjectList);exit;
        $subjectArr = array();
        foreach($subjectIdArr as $subjectId) {
            if(isset($subjectList[$subjectId])) {
                $subjectArr[$subjectId] = $subjectList[$subjectId]['lesson_name'];
            }
        }
        $this->subjectArr = $subjectArr;

        $majorId = $resultGrade['major_id'];
        $this->majorId = $majorId;
        $majorInfo = $this->dataModel->get_result_major_info($majorId);
        $this->majorTitle = $majorInfo['title'];
        $gradeInfo = $this->classesModel->get_grade_info($resultGrade['grade_id']);
        $this->gradeName = $gradeInfo['grade_name'];
        // 获取该年级所有的班级
        $classParams['schoolId'] = $this->rmxSchool['id'];
        $classParams['campusId'] = $this->campusInfo['id'];
        $classParams['isDelete'] = 0;
        $classParams['gradeId'] = $gradeInfo['id'];
        $this->classArr = $this->classesModel->get_class_list($classParams);

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "result_data");
    }
    // 获取成绩列表
    public function get_result_list($resultGradeId) {
        if(trim($this->get('realname'))) {
            $params['realname'] = $totalParams['realname'] = trim($this->get('realname'));
        }
        if($this->get('class_id')) {
            $params['classId'] = $totalParams['classId'] = $this->get('class_id');
        }
        // 获取数据
        $params['pageStart'] = $this->get('start');
        $params['pageSize']= $this->get("length");
        $params['resultGradeId'] = $resultGradeId;
        $params['isDelete'] = 0;
        $params['orderBy'] = '`total` DESC';
        $resultList = $this->dataModel->get_result_list($params);
        // echo '<pre>';var_export($resultList);exit;
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['resultGradeId'] = $resultGradeId;
        $totalParams['isDelete'] = 0;
        $total = $this->dataModel->get_result_list($totalParams);
        // 获取学校所有学生
        $stuParams['schoolId'] = $this->rmxSchool['id'];
        $stuParams['campusId'] = $this->campusInfo['id'];
        $stuParams['isDelete'] = 0;
        $studentList = $this->schoolModel->get_student_list($stuParams);
        // 用id作为键值
        $studentList = array_value_to_key($studentList, 'id');
        // 获取学校所有班级
        $classParams['schoolId'] = $this->rmxSchool['id'];
        $classParams['campusId'] = $this->campusInfo['id'];
        $classParams['isDelete'] = 0;
        $classList = $this->classesModel->get_class_list($classParams);
        // 用id作为键值
        $classList = array_value_to_key($classList, 'id');
        // 获取年级所有成绩
        $gradeResultList = $this->dataModel->get_result_list(array(
            'resultGradeId' => $resultGradeId,
            'isDelete' => 0,
            'orderBy' => '`total` DESC'
        ));
        foreach($gradeResultList as $key => $item) {
            $gradeResultList[$key]['rank'] = $key + 1;
            // 处理并列排名问题
            $loop = true;
            $i = 1;
            while($loop) {
                if($key - $i >= 0) {
                    if($gradeResultList[$key]['total'] == $gradeResultList[$key - $i]['total']) {
                        $gradeResultList[$key]['rank'] --;
                        $i++;
                    } else {
                        $loop = false;
                    }
                } else {
                    $loop = false;
                }
            }

            // var_export($item['total']);exit;
        }
        // 用id作为键值
        $gradeResultList = array_value_to_key($gradeResultList, 'id');
        $classIdArr = array();
        foreach($resultList as &$result) {
            $className = '';
            $classId = $result['class_id'];
            $className = $classList[$classId]['class_name'];
            $result['className'] = $className;
            // 处理value格式
            $valueArr = json_decode($result['value'], true);
            // 用id作为键值
            $valueArr = array_value_to_key($valueArr, 'subject_id');
            // $resArr = array();
            // foreach($valueArr as $item) {
            //     $subjectName = $item['subject_name'];
            //     $score = $item['score'];
            //     array_push($resArr, $subjectName . '：' . $score);
            // }
            // $result['value'] = implode(', ', $resArr);
            $result['value'] = $valueArr;
            // 处理total格式
            if(strstr($result['total'], '.0')) {
                $result['total'] = explode('.', $result['total'])[0];
            }
            // 年级排名
            $result['grade_rank'] = $gradeResultList[$result['id']]['rank'];
            // 获取班级id数组
            if(!in_array($classId, $classIdArr)) {
                array_push($classIdArr, $classId);
            }

        }
        // 获取各班级成绩
        $classResultArr = array();
        foreach($classIdArr as $classId) {
            $classResultList = $this->dataModel->get_result_list(array(
                'resultGradeId' => $resultGradeId,
                'classId' => $classId,
                'isDelete' => 0,
                'orderBy' => '`total` DESC'
            ));
            foreach($classResultList as $key => $item) {
                $classResultList[$key]['rank'] = $key + 1;
                // 处理并列排名问题
                $loop = true;
                $i = 1;
                while($loop) {
                    if($key - $i >= 0) {
                        if($classResultList[$key]['total'] == $classResultList[$key - $i]['total']) {
                            $classResultList[$key]['rank'] --;
                            $i++;
                        } else {
                            $loop = false;
                        }
                    } else {
                        $loop = false;
                    }
                }

            }
            // 用id作为键值
            $classResultList = array_value_to_key($classResultList, 'id');
            $classResultArr[$classId] = $classResultList;
        }
        if($classResultArr) {
            // 班级排序
            foreach($resultList as $key => $item) {
                $resultList[$key]['class_rank'] = $classResultArr[$item['class_id']][$item['id']]['rank'];
            }
        }
        // echo '<pre>';var_export($resultList);exit;
        // 返回值
        exit(admin_table_data($total, $resultList));
    }
    // 编辑成绩页面
    public function edit_result_page() {
        $resultGradeId = $this->get('result_grade_id');
        if(empty($resultGradeId)){
            throw new Exception('id不能为空');
        }
        $resultId = $this->get('result_id');
        if(!empty($resultId)){
            $this->resultId = $resultId;
            $result = $this->dataModel->get_result_info($resultId);
            // 获取学生姓名
            $student = $this->schoolModel->get_student_info($result['student_id']);
            $result['realname'] = $student['realname'];
            // 获取分数数组
            $valueArr = json_decode($result['value'], true);
            $scoreArr = array();
            foreach($valueArr as $item) {
                $subjectId = $item['subject_id'];
                $scoreArr[$subjectId] = $item['score'];
            }
            $result['scoreArr'] = $scoreArr;
            $this->result = $result;
        }
        $resultGradeInfo = $this->dataModel->get_result_grade_info($resultGradeId);
        // 年级id
        $this->gradeId = $resultGradeInfo['grade_id'];
        // 年级项id
        $this->resultGradeId = $resultGradeId;
        // 获取学校所有科目
        $lesParams['schoolId'] = $this->rmxSchool['id'];
        $lesParams['isDelete'] = 0;
        $subjectArr = $this->schoolModel->get_lesson_list($lesParams);
        // 用id作为键值
        $subjectArr = array_value_to_key($subjectArr, 'id');
        // 获取考试科目数组
        if(empty($resultGradeInfo['subject_ids'])) {
            $subjectIdArr = array();
        } else {
            $subjectIdArr = explode(',', $resultGradeInfo['subject_ids']);
        }
        $resultGradeSubjectArr = array();
        foreach($subjectIdArr as $subjectId) {
            array_push($resultGradeSubjectArr, $subjectArr[$subjectId]);
        }
        $this->resultGradeSubjectArr = $resultGradeSubjectArr;
        // echo '<pre>';var_export($resultGradeSubjectArr);exit;
        $this->display(ADMIN_DIR . DIRECTORY_SEPARATOR . "contents" . DIRECTORY_SEPARATOR . "edit_result_page");
    }
    // 保存成绩
    public function save_result_action() {
        $resultGradeId = $this->post('result_grade_id');
        $resultId = $this->post('result_id');
        $remark = trim($this->post('remark')) ? trim($this->post('remark')) : '';
        // 获取年级项信息
        $resultGradeInfo = $this->dataModel->get_result_grade_info($resultGradeId);
        // 获取学校所有科目
        $lesParams['schoolId'] = $this->rmxSchool['id'];
        $lesParams['isDelete'] = 0;
        $subjectArr = $this->schoolModel->get_lesson_list($lesParams);
        // 用id作为键值
        $subjectArr = array_value_to_key($subjectArr, 'id');
        // 获取考试科目数组
        if(empty($resultGradeInfo['subject_ids'])) {
            $subjectIdArr = array();
        } else {
            $subjectIdArr = explode(',', $resultGradeInfo['subject_ids']);
        }
        $resultGradeSubjectArr = array();
        foreach($subjectIdArr as $subjectId) {
            array_push($resultGradeSubjectArr, $subjectArr[$subjectId]);
        }
        $value = '';
        $valueArr = array();
        $total = 0;
        foreach($resultGradeSubjectArr as $subject) {
            $score = $this->post($subject['id']);
            $score = (float) $score;
            if(!is_numeric($score) || $score < 0 || $score > 150) {
                throw new Exception('分数格式不正确');
            }

            $total += (float) $score;
            $arr = array(
                'subject_id' => $subject['id'],
                'subject_name' => $subject['lesson_name'],
                'score' => $score
            );
            array_push($valueArr, $arr);
        }
        $value = json_encode($valueArr, JSON_UNESCAPED_UNICODE);
        if(empty($resultId)) {
            $studentId = $this->post('student_id');
            if(empty($studentId)) {
                throw new Exception('请选择学生');
            }
            $studentInfo = $this->schoolModel->get_student_info($studentId);
            // 判断该学生成绩是否已添加过
            $resultInfo = $this->dataModel->get_result_info_by_student_id($resultGradeId, $studentId);
            if($resultInfo) {
                throw new Exception('该学生成绩已存在');
            }
            // 添加操作
            $this->db->insert(DataModel::$resultTable, array(
                'result_grade_id' => $resultGradeId,
                'student_id' => $studentInfo['id'],
                'value' => $value,
                'total' => $total,
                'remark' => $remark,
                'is_delete' => 0,
                'createtime' => date('Y-m-d H:i:s'),
                'updatetime' => date('Y-m-d H:i:s')
            ));
            $msg = '添加成功';
        } else {
            // 修改操作;
            $this->db->update(DataModel::$resultTable, array(
                'value' => $value,
                'total' => $total,
                'remark' => $remark,
                'updatetime' => date('Y-m-d H:i:s')
            ), "id = {$resultId}");
            $msg = '修改成功';
        }
        exit(json($msg, true));
    }
    // 删除成绩
    public function delete_result_action(){
        $id = $this->post('result_id');
        if(empty($id)){
            throw new Exception('id不能为空');
        }
        // 删除成绩大项
        $arr = array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->where('id', $id);
        $this->db->update(DataModel::$resultTable, $arr);
      
        exit(json('删除成功', true));
    }

    // 批量删除作业
    public function delete_homework_batch(){
        $idArr = $this->post('id_arr');
        if(empty($idArr) || count($idArr) === 0){
            throw new Exception("请先勾选要删除的作业");
        }
        $idArr = array_unique($idArr);
        $data = array();
        foreach($idArr as $id){
            $data[] = array(
                'id' => $id,
                'is_delete' => 1,
                'updatetime' => date('Y-m-d H:i:s')
            );
        }
        $this->db->update_batch(ContentModel::$homeworkTable, $data, 'id');

        // 插入日志
        $this->load->library('logger');
        $actionName = 'delete';
        $actionType = $this->logger->get_action_type($actionName);
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' => '批量删除作业，个数：' . count($idArr)
        ));

        exit(json('删除成功', true));
    }

    // 批量删除动态
    public function delete_news_batch(){
        $idArr = $this->post('id_arr');
        if(empty($idArr) || count($idArr) === 0){
            throw new Exception("请先勾选要删除的动态");
        }
        $idArr = array_unique($idArr);
        $data = array();
        foreach($idArr as $id){
            $data[] = array(
                'id' => $id,
                'is_delete' => 1,
                'updatetime' => date('Y-m-d H:i:s')
            );
        }
        $this->db->update_batch(ContentModel::$newsTable, $data, 'id');

        // 插入日志
        $this->load->library('logger');
        $actionName = 'delete';
        $actionType = $this->logger->get_action_type($actionName);
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' => '批量删除动态，个数：' . count($idArr)
        ));

        exit(json('删除成功', true));
    }

    // 批量删除通知
    public function delete_notify_batch(){
        $idArr = $this->post('id_arr');
        if(empty($idArr) || count($idArr) === 0){
            throw new Exception("请先勾选要删除的通知");
        }
        $idArr = array_unique($idArr);
        $data = array();
        foreach($idArr as $id){
            $data[] = array(
                'id' => $id,
                'is_delete' => 1,
                'updatetime' => date('Y-m-d H:i:s')
            );
        }
        $this->db->update_batch(ContentModel::$notifyTable, $data, 'id');

        // 插入日志
        $this->load->library('logger');
        $actionName = 'delete';
        $actionType = $this->logger->get_action_type($actionName);
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' => '批量删除通知，个数：' . count($idArr)
        ));

        exit(json('删除成功', true));
    }
    // 主题
    public function subject_content(){
        // 获取年级
        $gradeParams['isDelete'] = 0;
        $gradeParams['schoolId'] = $this->rmxSchool['id'];
        $gradeParams['campusId'] = $this->campusInfo['id'];
        $this->gradeList = $this->classesModel->get_grade_list($gradeParams);
        // 只获取行政班
        $gradeParams['classType'] = CLASSES_TYPE_NORMAL;

        // 获取班级列表
        $classData = $this->classesModel->get_class_list($gradeParams);
        $classArray = array();
        foreach($classData as $class) {
            $classArray[$class['grade_id']][] = array(
                "id" => $class['id'],
                "name" => $class['class_name']
            );
        }
        $this->classList = json_encode($classArray);
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "subject_content");
    }
    // 主题列表
    public function subject_content_list($classId){
        $this->classInfo = $classInfo = $this->classesModel->get_class_info($classId);
        if(!$classInfo || $classInfo['school_id'] != $this->rmxSchool['id'])show_error("参数不错，班级不存在");

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "subject_content_list");
    }
    // ajax获取主题列表
    public function get_subject_content_list() {
        // 默认获取当前校区的所有班级
        $classIdArr = $this->_get_campus_class_id_Arr();
        // 筛选班级
        if($this->get('class_id') && 0 !== $this->get('class_id')) {
            $classId = $this->get('class_id');
            $data['classId'] = $classId;
            $totalParams['classId'] = $classId;
        }
        // 搜索标题
        if($this->get('title') && '' !== trim($this->get('title'))) {
            $title = trim($this->get('title'));
        }
        // 是否生效中
        if($this->get('effect')) {
            if($this->get('effect') == 1) {
                $data['effective'] = $totalParams['effective'] = 1;
            } else if($this->get('effect') == 2) {
                $data['uneffective'] = $totalParams['uneffective'] = 1;
            }
        }
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        // 过滤软删除
        $data['isDelete'] = 0;
        // 过滤班级数组
        if($classIdArr) {
            $data['classIdArr'] = $classIdArr;
        }
        // 过滤标题
        if(isset($title)) {
            $data['title'] = $title;
        }
        // 教师权限登录时，只获取任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER && isset($this->rmxUser['classIdArr'])) {
            $data['classIdArr'] = $this->rmxUser['classIdArr'];
        }
        $subjectContentList = $this->contentModel->get_subject_content_list($data);
        foreach($subjectContentList as &$subjectContent) {
            // 查询主题发送班级
            $params['classId'] = $subjectContent['class_id'];
            // 过滤软删除
            $params['isDelete'] = 0;
            $subjectContent['classList'] = $this->classesModel->get_grade_class_list($params);
            // 判断当前用户有没编辑权限
            $subjectContent['role_change'] = true;
            if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
                $subjectContent['role_change'] = false;
                $idArr = explode(',', $subjectContent['class_id']);
                foreach($idArr as $id) {
                    if(in_array($id, $this->rmxUser['classIdArr'])) {
                        $subjectContent['role_change'] = true;
                    }
                }
            }
            // 是否生效中
            $subjectContent['isEffect'] = true;
            // 生效和失效时间
            if($subjectContent['begintime'] > date('Y-m-d H:i')) {
                $subjectContent['begintime'] = "<span class='text-danger'>{$subjectContent['begintime']}</span>";
                // 非生效中
                $subjectContent['isEffect'] = false;
            }
            if($subjectContent['endtime'] < date('Y-m-d H:i')) {
                $subjectContent['endtime'] = "<span class='text-danger'>{$subjectContent['endtime']}</span>";
                // 非生效中
                $subjectContent['isEffect'] = false;
            }
        }
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $totalParams['isDelete'] = 0;
        // 过滤班级数组
        if($classIdArr) {
            $totalParams['classIdArr'] = $classIdArr;
        }
        // 过滤标题
        if(isset($title)) {
            $totalParams['title'] = $title;
        }
        // 教师权限登录时，只获取任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER && isset($this->rmxUser['classIdArr'])) {
            $totalParams['classIdArr'] = $this->rmxUser['classIdArr'];
        }
        $total = $this->contentModel->get_subject_content_list($totalParams);
        // echo '<pre>';var_export($subjectContentList);exit;
        foreach($subjectContentList as $key => $item) {
          
        }

        // 返回值
        exit(admin_table_data($total, $subjectContentList));   
    }
    // 编辑主题页面
    public function subject_content_edit($subjectContentId = 0){
        // 类型
        $this->type = $this->get('type');
        switch ($this->type) {
            case SUBJECT_CONTENT_TYPE_IMAGE_AND_TEXT:
                $this->typeTitle = '图文主题';
                break;
            case SUBJECT_CONTENT_TYPE_VIDEO:
                $this->typeTitle = '视频主题';
                break;
        }

        if(!empty($subjectContentId)) {
            $this->subjectContentInfo = $this->contentModel->get_subject_content_info($subjectContentId);
            if(trim($this->subjectContentInfo['videos'])) {
                $videoArr = json_decode($this->subjectContentInfo['videos'], true);
                foreach($videoArr as &$video) {
                    if(isset($video['old_link']) && stripos($video['old_link'], '.MOV') === false) {
                        $video['href'] = $video['old_link'];
                    } else {
                        $video['href'] = $video['link'];
                    }
                }
                $this->subjectContentInfo['videoArr'] = $videoArr;
                // echo '<pre>';var_export($this->subjectContentInfo['videoArr']);exit;
            }
        }
        $params['isDelete'] = 0;
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['getLevelData'] = true;
        // 教师权限只能发布任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
            $params['classId'] = $this->rmxUser['class_ids'];
        }
        // 只获取行政班
        $params['classType'] = CLASSES_TYPE_NORMAL;

        $this->gradeArray = $this->classesModel->get_grade_class_list($params);
        // 生成又拍云签名
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "subject_content_edit");
    }
    // 保存班级主题
    public function save_subject_content_action(){
        $type = $this->post("type") ? $this->post("type") : SUBJECT_CONTENT_TYPE_IMAGE_AND_TEXT;
        $subjectContentId = $this->post("id");
        $title = $this->post("title");
        $subjectContentClass = $this->post("subject_content_class");
        $begintime = $this->post('begintime');
        $endtime = $this->post('endtime');
        $playInClassMode = $this->post("play_in_class_mode") ? $this->post("play_in_class_mode") : 0;
        $isFullScreen = $this->post("is_full_screen") ? $this->post("is_full_screen") : 0;
        $content = '';
        $videos = '';
        if($type == SUBJECT_CONTENT_TYPE_IMAGE_AND_TEXT) {
            $content = $this->post("content", false);
            if(!$content) throw new Exception("请填写内容");
        } else if($type == SUBJECT_CONTENT_TYPE_VIDEO) {
            if($this->post('video_arr') && 9 < count($this->post('video_arr'))) {
                throw new Exception("最多只能上传9个视频");
            }
            $videos = $this->post('video_arr') ? json_encode($this->post('video_arr'), JSON_UNESCAPED_UNICODE) : '';
            if(empty($videos)) {
                throw new Exception("请上传视频");
            }
        }

        if($begintime >= $endtime) {
            throw new Exception("生效时间必须小于失效时间");
        }
        // 参数检查
        if(!$title) throw new Exception("请填写标题");
        if(!$subjectContentClass) throw new Exception("请选择发送班级");

        // 提示信息
        $msg = $subjectContentId ? '修改主题成功' : '发布主题成功';

        // 入库
        $data['class_id'] = $subjectContentClass;
        $data['title'] = $title;
        $data['content'] = $content;
        $data['videos'] = $videos;
        $data['begintime'] = $begintime;
        $data['endtime'] = $endtime;
        $data['type'] = $type;
        $data['play_in_class_mode'] = $playInClassMode;
        $data['is_full_screen'] = $isFullScreen;
        $data['updatetime'] = date("Y-m-d H:i:s");
        if($subjectContentId) {
            $this->db->update(ContentModel::$subjectContentTable, $data, "id='{$subjectContentId}'");
        } else {
            $data['school_id'] = $this->rmxSchool['id'];
            $data['campus_id'] = $this->campusInfo['id'];
            $data['user_id'] = $this->rmxUser['id'];
            $data['createtime'] = $data['updatetime'];
            $this->db->insert(ContentModel::$subjectContentTable, $data);
        }

        // 返回值
        exit(json($msg, true));
    }

    // 删除主题
    public function delete_subject_content_action() {
        $id = $this->post('id');
        $data = array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(ContentModel::$subjectContentTable, $data, array('id' => $id));
        exit(json('删除成功', true));
    }

    // 年级作息列表页面
    public function grade_schedule(){


        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "grade_schedule");
    }

    // 年级作息详情页面
    public function grade_schedule_detail($gradeId, $scheduleId = 0){
        // var_export($scheduleId); exit;
        // 获取年级作息列表
        $scheduleParams['isDelete'] = 0;
        $scheduleParams['schoolId'] = $this->rmxSchool['id'];
        $scheduleParams['campusId'] = $this->campusInfo['id'];
        $scheduleParams['gradeId'] = $gradeId;
        $scheduleParams['orderBy'] = '`week` ASC';
        $scheduleList = $this->classesModel->get_school_schedule($scheduleParams);
        // 获取星期
        $this->load->helper('schedule');
        if($scheduleList) {
            foreach($scheduleList as &$schedule) {
                $weekArr = explode(',', $schedule['week']);
                $weekChineseArr = array();
                foreach($weekArr as $week) {
                    $weekChineseArr[] = transform_schedule_week_to_chinese_long($week);
                }
                $schedule['weekChinese'] = implode('、', $weekChineseArr);
            }
        }

        if($scheduleId) {
            // 有选中具体的星期
            $scheduleInfo = $this->classesModel->get_school_schedule_info($scheduleId);
        } else {
            // 默认选中第一个
            $scheduleInfo = $scheduleList[0];
            $scheduleId = $scheduleInfo['id'];
        }
        $timeArr = json_decode($scheduleInfo['schedule_time_json'], true);
        if(!empty($timeArr)) {
            foreach($timeArr as $key => $time) {
                // 计算课程结束时间
                $timeArr[$key]['endTime'] = add_time($time['beginTime'], $time['duration']);
                // 计算考勤开始时间
                $signInterval = isset($time['sign_interval']) ? $time['sign_interval'] : 10;
                $timeArr[$key]['sign_interval'] = $signInterval;
                $timeArr[$key]['signBeginTime'] = subtract_time($time['beginTime'], $signInterval);
                $timeArr[$key]['signEndTime'] = $time['beginTime'];
                $timeArr[$key]['refresh'] = isset($time['refresh']) ? $time['refresh'] : '否';
            }
        }
        $scheduleInfo['timeArr'] = $timeArr;

        $gradeInfo = $this->classesModel->get_grade_info($gradeId);
        $this->scheduleId = $scheduleId;
        $this->scheduleInfo = $scheduleInfo;
        $this->scheduleList = $scheduleList;
        $this->gradeInfo = $gradeInfo;

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "contents". DIRECTORY_SEPARATOR. "grade_schedule_detail");
    }

    // 开启不同年级作息
    public function toggle_grade_schedule_action() {
        // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
        $onlyOneSchedule = $this->classesModel->check_is_only_one_schedule($this->rmxSchool['id'], $this->campusInfo['id']);
        if($onlyOneSchedule) {
            // 开启不同年级作息
            // 获取全校作息
            $scheduleParams['isDelete'] = 0;
            $scheduleParams['schoolId'] = $this->rmxSchool['id'];
            $scheduleParams['campusId'] = $this->campusInfo['id'];
            $scheduleParams['gradeId'] = 0;
            $scheduleList = $this->classesModel->get_school_schedule($scheduleParams);
            $scheduleInfo = $scheduleList[0];
            // 删除全校作息
            $this->db->update(ClassesModel::$scheduleTable, array(
                'is_delete' => 1,
                'updatetime' => date('Y-m-d H:i:s')
            ), array('id' => $scheduleInfo['id']));
            // 新建各年级作息
            $gradeParams['isDelete'] = 0;
            $gradeParams['schoolId'] = $this->rmxSchool['id'];
            $gradeParams['campusId'] = $this->campusInfo['id'];
            $gradeParams['excludeFunctional'] = 1; // 排除功能课室
            $gradeList = $this->classesModel->get_grade_list($gradeParams);
            foreach($gradeList as $grade) {
                // 判断该年级作息是否已存在
                $gradeScheduleParams['schoolId'] = $this->rmxSchool['id'];
                $gradeScheduleParams['campusId'] = $this->campusInfo['id'];
                $gradeScheduleParams['gradeId'] = $grade['id'];
                $gradeScheduleList = $this->classesModel->get_school_schedule($gradeScheduleParams);
                if($gradeScheduleList) {
                    $gradeScheduleInfo = $gradeScheduleList[0];
                    // 更新is_delete
                    $this->db->update(ClassesModel::$scheduleTable, array(
                        'is_delete' => 0,
                        'updatetime' => date('Y-m-d H:i:s')
                    ), array('id' => $gradeScheduleInfo['id']));
                } else {
                    // 新建该年级作息
                    $timeJson = '[{"timeslotInDay":1,"beginTime":"08:00","duration":45,"breakDuration":10},{"timeslotInDay":2,"beginTime":"08:55","duration":45,"breakDuration":10},{"timeslotInDay":3,"beginTime":"09:50","duration":45,"breakDuration":10},{"timeslotInDay":4,"beginTime":"10:45","duration":45,"breakDuration":150},{"timeslotInDay":5,"beginTime":"14:00","duration":45,"breakDuration":10},{"timeslotInDay":6,"beginTime":"14:55","duration":55,"breakDuration":10},{"timeslotInDay":7,"beginTime":"16:00","duration":45,"breakDuration":10}]';
                    $saveGradeScheduleDataArr = array(
                        'school_id' => $this->rmxSchool['id'],
                        'campus_id' => $this->campusInfo['id'],
                        'grade_id' => $grade['id'],
                        'schedule_title' => $grade['grade_name'] . '-年级作息',
                        // 现在只使用本周课程数据
                        'schedule_this_week' => 1,
                        'schedule_week_days' => 7,
                        'schedule_morning_number' => 4,
                        'schedule_afternoon_number' => 3,
                        'schedule_time_json' => $timeJson,
                        'week' => '1,2,3,4,5,6,7',
                        'createtime' => date('Y-m-d H:i:s'),
                        'updatetime' => date('Y-m-d H:i:s')
                    );
                    $this->db->insert(ClassesModel::$scheduleTable, $saveGradeScheduleDataArr);
                }
            }
        } else {
            // 关闭不同年级作息
            // 先删除所有作息，在开启全校作息
            $this->db->update(ClassesModel::$scheduleTable, array(
                'is_delete' => 1,
                'updatetime' => date('Y-m-d H:i:s')
            ), array('school_id' => $this->rmxSchool['id']));
            // 获取全校作息
            $scheduleParams['schoolId'] = $this->rmxSchool['id'];
            $scheduleParams['campusId'] = $this->campusInfo['id'];
            $scheduleParams['gradeId'] = 0;
            $scheduleList = $this->classesModel->get_school_schedule($scheduleParams);
            if($scheduleList) {
                $scheduleInfo = $scheduleList[0];
                // 开启全校作息
                $this->db->update(ClassesModel::$scheduleTable, array(
                    'is_delete' => 0,
                    'updatetime' => date('Y-m-d H:i:s')
                ), array('id' => $scheduleInfo['id']));
            } else {
                // 新建全校作息
                // 新建该年级作息
                $timeJson = '[{"timeslotInDay":1,"beginTime":"08:00","duration":45,"breakDuration":10},{"timeslotInDay":2,"beginTime":"08:55","duration":45,"breakDuration":10},{"timeslotInDay":3,"beginTime":"09:50","duration":45,"breakDuration":10},{"timeslotInDay":4,"beginTime":"10:45","duration":45,"breakDuration":150},{"timeslotInDay":5,"beginTime":"14:00","duration":45,"breakDuration":10},{"timeslotInDay":6,"beginTime":"14:55","duration":55,"breakDuration":10},{"timeslotInDay":7,"beginTime":"16:00","duration":45,"breakDuration":10}]';
                $scheduleDataArr = array(
                    'school_id' => $this->rmxSchool['id'],
                    'campus_id' => $this->campusInfo['id'],
                    'grade_id' => 0,
                    'schedule_title' => '全校作息',
                    // 现在只使用本周课程数据
                    'schedule_this_week' => 1,
                    'schedule_week_days' => 7,
                    'schedule_morning_number' => 4,
                    'schedule_afternoon_number' => 3,
                    'schedule_time_json' => $timeJson,
                    'createtime' => date('Y-m-d H:i:s'),
                    'updatetime' => date('Y-m-d H:i:s')
                );
                $this->db->insert(ClassesModel::$scheduleTable, $scheduleDataArr);
            }
        }
        // 切换成功，删除全校课程
        $this->db->update(ClassesModel::$scheduleLessonTable, array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s')
        ), array(
            'is_delete' => 0,
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
        ));
        // echo '<pre>';var_export($onlyOneSchedule);exit;

        $actionName = $onlyOneSchedule ? '开启' : '关闭';
        exit(json($actionName . '成功', true));
    }

    // 自动填充任课教师
    public function auto_complete_schedule_teacher() {
        $this->load->model('staffModel');
        // // 获取任课老师列表
        // $coachParams['schoolId'] = $this->rmxSchool['id'];
        // $coachParams['campusId'] = $this->campusInfo['id'];
        // $coachParams['coachType'] = COACH_TYPE_TEACHER;
        // $coachList = $this->staffModel->get_coach_list($coachParams);

        // 获取本校全部科目
        $lessonParams['schoolId'] = $this->rmxSchool['id'];
        $lessonParams['isDelete'] = 0;
        $lessonList = $this->schoolModel->get_lesson_list($lessonParams);
        $lessonList = array_value_to_key($lessonList, 'lesson_name');
        // 获取课表
        $lessonParams['isDelete'] = 0;
        $lessonParams['schoolId'] =  $this->rmxSchool['id'];
        $lessonParams['teacherId'] = 0;
        $scheduleLessons = $this->classesModel->get_school_schedule_lesson($lessonParams);
        $updateBatch = array();
        foreach($scheduleLessons as $item) {
            $subjectName = $item['schedule_lesson'];
            $classId = $item['class_id'];
            if(isset($lessonList[$subjectName])) {
                $subjectId = $lessonList[$subjectName]['id'];
                // 根据班级id,课程id，获取任课老师

                $coachParams['schoolId'] = $this->rmxSchool['id'];
                $coachParams['campusId'] = $this->campusInfo['id'];
                $coachParams['coachType'] = COACH_TYPE_TEACHER;
                $coachParams['classId'] = $classId;
                $coachParams['subjectId'] = $subjectId;
                $coachList = $this->staffModel->get_coach_list($coachParams);
                // echo '<pre>';var_export($coachList);exit;
                if($coachList) {
                    $teacherId = 0;
                    foreach($coachList as $coach) {
                        if($coach['teacher_id']) {
                            $teacherId = $coach['teacher_id'];
                        }
                    }
                    if($teacherId) {
                        $updateBatch[] = array(
                            'id' => $item['id'],
                            'schedule_teacher' => $teacherId,
                            'updatetime' => date('Y-m-d H:i:s')
                        );
                    }
                }
            }

        }
        if($updateBatch) {
            $this->db->update_batch(DataModel::$scheduleLessonTable, $updateBatch, 'id');
        }
        $msg = '执行成功，';
        $msg .= '插入了' . count($updateBatch). '条数据';
        exit(json($msg, true));
        // echo '<pre>';var_export($updateBatch);exit;
    }
}